Home  >  Article  >  Java  >  Object pool design pattern

Object pool design pattern

WBOY
WBOYforward
2023-08-19 16:29:21612browse

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.com. If there is any infringement, please contact admin@php.cn delete