search
HomeJavajavaTutorialObject pool design pattern

Object pool design pattern

Aug 19, 2023 pm 04:29 PM
Design Patternsobject poolProgramming keywords

Object pool design pattern

A software design pattern often used in Java programming is the object pool design pattern. This mode controls how objects in the object pool are created and destroyed.

Use the object pool design pattern to manage the production and destruction of objects. The concept of this pattern is to accumulate reusable objects instead of creating new ones every time they are needed. For situations where the cost of producing new objects is significant, such as network connections, database connections, or expensive objects, Java programmers often use the object pool design pattern.

Syntax of object pool design

In Java, the syntax of the object pool design pattern is as follows −

  • Create a fixed-size object collection.

  • Initialize the project of the pool.

  • Track items currently in the pool.

  • Whenever needed, check if there is an accessible object in the pool.

  • Please make sure to promptly retrieve any available objects from the pool yourself and return them appropriately as needed

  • However, if there is no item currently available in this repository - we request that a new item be created immediately to avoid wasting time or resources and then put back into circulation.

Different algorithms for object pool design

The Java object pool design pattern can be used for various algorithms. Here are three possible strategies, each with unique code implementations:

Lazy initialization and synchronization

import java.util.ArrayList;
import java.util.List;

public class ObjectPool {
   private static ObjectPool instance;
   private List<Object> pool = new ArrayList<>();
   private int poolSize;

   private ObjectPool() {}
   
   public static synchronized ObjectPool getInstance(int poolSize) {
      if (instance == null) {
         instance = new ObjectPool();
         instance.poolSize = poolSize;
         for (int i = 0; i < poolSize; i++) {
            instance.pool.add(createObject());
         }
      }
      return instance;
   }

   private static Object createObject() {
      // Create and return a new object instance
      return new Object();
   }

   public synchronized Object getObject() {
      if (pool.isEmpty()) {
         return createObject();
      } else {
         return pool.remove(pool.size() - 1);
      }
   }

   public synchronized void releaseObject(Object object) {
      if (pool.size() < poolSize) {
         pool.add(object);
      }
   }
}

The technique used here emphasizes thread safety through initialization of an accordingly lazy and synchronized object pool with preset capacity limitations that are amendable to expansion. Empty pools result in safe new instance production, while non-full instances are carefully reintroduced to maintain proper operational integrity.

Eager initialization using concurrent data structures

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class ObjectPool {
   private static final int POOL_SIZE = 10;
   private static ObjectPool instance = new ObjectPool();
   private BlockingQueue<Object> pool = new LinkedBlockingQueue<>(POOL_SIZE);

   private ObjectPool() {
      for (int i = 0; i < POOL_SIZE; i++) {
         pool.offer(createObject());
      }
   }

   private static Object createObject() {
      // Create and return a new object instance
      return new Object();
   }

   public static ObjectPool getInstance() {
      return instance;
   }

   public Object getObject() throws InterruptedException {
      return pool.take();
   }

   public void releaseObject(Object object) {
      pool.offer(object);
   }
}

In this implementation, a static final instance variable is used to eagerly initialize the object pool. The underlying data structure is a LinkedBlockingQueue, which provides thread safety without the need for synchronization. During initialization, objects are added to the pool and when needed they are retrieved from the queue using take(). When an item is released, use offer() to requeue it.

Time-based expiration

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

public class ObjectPool {
   private static final int POOL_SIZE = 10;
   private static ObjectPool instance = new ObjectPool();
   private BlockingQueue<Object> pool = new LinkedBlockingQueue<>(POOL_SIZE);

   private ObjectPool() {}

   private static Object createObject() {
      // Create and return a new object instance
      return new Object();
   }

   public static ObjectPool getInstance() {
      return instance;
   }

   public Object getObject() throws InterruptedException {
      Object object = pool.poll(100, TimeUnit.MILLISECONDS);
      if (object == null) {
         object = createObject();
      }
      return object;
   }

   public void releaseObject(Object object) {
      pool.offer(object);
   }

}

The object pool in this version uses a time-based expiration mechanism instead of a fixed size. When an object is needed, the poll() function is used to remove the object from the pool. When there is no available object, the function will wait for a period of time and return null. Objects are generated on demand. If no object exists, a new object will be generated and returned. When an object is released, use offer() to put it back into the pool. The expireObjects() function is used to remove expired items from the pool based on the provided timeout value.

Different ways to use the object pool design pattern

Java’s object pool design pattern can be implemented in a variety of ways. Below are two typical methods, including code examples and results −

Method 1: Simple object pool design pattern

One way to build a simple and practical object pool is to use an array-based approach. This approach works as follows: once fully generated, all objects are included in the corresponding "pool" array for future use; at runtime, the collection is checked to determine if any of the required items are available. If it can be obtained from existing inventory, it will be returned immediately; otherwise, another new object will be generated based on demand.

Example

public class ObjectPool {
   private static final int POOL_SIZE = 2;
   private static List<Object> pool = new ArrayList<Object>(POOL_SIZE);
    
   static {
      for(int i = 0; i < POOL_SIZE; i++) {
         pool.add(new Object());
      }
   }
    
   public static synchronized Object getObject() {
      if(pool.size() > 0) {
         return pool.remove(0);
      } else {
         return new Object();
      }
   }
    
   public static synchronized void releaseObject(Object obj) {
      pool.add(obj);
   }
}

Example

public class ObjectPoolExample {
   public static void main(String[] args) {
      Object obj1 = ObjectPool.getObject();
      Object obj2 = ObjectPool.getObject();
        
      System.out.println("Object 1: " + obj1.toString());
      System.out.println("Object 2: " + obj2.toString());
        
      ObjectPool.releaseObject(obj1);
      ObjectPool.releaseObject(obj2);
        
      Object obj3 = ObjectPool.getObject();
      Object obj4 = ObjectPool.getObject();
        
      System.out.println("Object 3: " + obj3.toString());
      System.out.println("Object 4: " + obj4.toString());
   }
}

Output

Object 1: java.lang.Object@4fca772d
Object 2: java.lang.Object@1218025c
Object 3: java.lang.Object@4fca772d
Object 4: java.lang.Object@1218025c

Method 2: Universal Object Pool Design Pattern

Using lists as a basis, this technique facilitates building a standard object pool, storing objects in the collection until they are completely generated and included in the collection. Whenever access to an item is required, the system browses the available options in the pool. If there is one option available, that is sufficient; but if none is available, another new project must be created.

Example

import java.util.ArrayList;
import java.util.List;

public class ObjectPool<T> {
   private List<T> pool;
    
   public ObjectPool(List<T> pool) {
      this.pool = pool;
   }
    
   public synchronized T getObject() {
      if (pool.size() > 0) {
         return pool.remove(0);
      } else {
         return createObject();
      }
   }
    
   public synchronized void releaseObject(T obj) {
      pool.add(obj);
   }
    
   private T createObject() {
      T obj = null;
      // create object code here
      return obj;
   }
    
   public static void main(String[] args) {
      List<String> pool = new ArrayList<String>();
      pool.add("Object 1");
      pool.add("Object 2");
        
      ObjectPool<String> objectPool = new ObjectPool<String>(pool);
        
      String obj1 = objectPool.getObject();
      String obj2 = objectPool.getObject();
        
      System.out.println("Object 1: " + obj1);
      System.out.println("Object 2: " + obj2);
        
      objectPool.releaseObject(obj1);
      objectPool.releaseObject(obj2);
        
      String obj3 = objectPool.getObject();
      String obj4 = objectPool.getObject();
        
      System.out.println("Object 3: " + obj3);
      System.out.println("Object 4: " + obj4);
   }
}

Output

Object 1: Object 1
Object 2: Object 2
Object 3: Object 1
Object 4: Object 2

Best practices for using class-level locks

When the cost of producing new objects is high, Java programmers often use the object pool design pattern. Typical usage scenarios include −

Internet connection

In a Java program, network connections may be managed using the Object Pool Design Pattern. It is preferable to reuse existing connections from a pool rather than having to create new ones every time one is required. This may enhance the application's functionality while lightening the burden on the network server.

Database Connectivity

Similar to network connection management, Java applications can also use the object pool design pattern to handle database connections. It's better to reuse an existing connection from the pool rather than create a new one every time a database connection is needed. This can improve application performance and reduce the load on the database server.

Thread Pool

Developers using Java programs should adopt the object pool design pattern to effectively manage thread pools. Rather than re-creating each required thread as needed, well-planned usage relies on reusing pre-existing threads that are available in a designated workgroup. Therefore, it encourages optimal application performance by keeping the overhead of thread creation and termination processes low, driven by the efficiency of the structure.

Image Processing

When dealing with intensive image processing tasks in Java programs, it is worth considering implementing the object pool design pattern. By leveraging pre-existing objects from a dedicated pool, you can speed up your application's performance while reducing the overall computing demands of your photo editing tasks.

File system operations

If you are facing heavy image processing tasks in a Java application, it is worth considering applying the object pool design pattern. This technique utilizes existing items in a specific pool to increase the program's output speed and reduce the computing resources required to edit photos.

in conclusion

The object pool design pattern is a useful design pattern in Java programming, suitable for situations where the cost of creating new objects is high. It provides a way to control the supply of reusable objects, reducing the overall cost of creating new products. Simple Object Pool or Generic Object Pool are two examples of implementing the Object Pool design pattern. The object pool design pattern is often used in Java programming to handle expensive objects, such as database connections and network connections. It is similar in purpose to Flyweight pattern and Singleton pattern, but has different uses.

The above is the detailed content of Object pool design pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor