What is object pool in java

Object Pool Design Pattern in Java

Object Pool Design Pattern in Java with Examples

In this article, I am going to discuss Object Pool Design Pattern in Java with Examples. Please read our previous article where we discussed Builder Design Patterns in Java with Examples. The Object Pool Design Pattern falls under the category of the Creational Design Pattern. In this article, we will explore the fundamental principles, advantages, and potential disadvantages of the Object Pool Design Pattern, emphasizing its significance inefficient object reuse and resource management.

What is an Object Pool Design Pattern?

In software development, there are scenarios where creating and destroying objects frequently can be inefficient and resource-intensive. The Object Pool design pattern provides a solution by reusing and managing a pool of pre-initialized objects. By maintaining a pool of reusable objects, the pattern eliminates the overhead of object creation and destruction, improving performance and resource utilization.

  • Object Pool: Manages the pool of reusable objects and provides methods to acquire and release objects from the pool.
  • Reusable Objects: Objects that are pre-initialized and maintained in the object pool. These objects are returned to the pool after being used, instead of being destroyed.
Example to Understand Advantages Object Pool Design Pattern in Java

Let’s consider a real-world example where the Object Pool pattern can be applied: a pool of resources. In many software systems, establishing a resource is a time-consuming process. However, applications often require multiple resources to handle simultaneous user requests efficiently.

The Object Pool pattern can be used to create a pool of resources. When the application requires a resource, it can acquire a resource from the pool instead of creating a new one. Once the resource is no longer required, it can be released back to the pool, ready to be reused by another part of the application.

Читайте также:  Php does path exist

The Object Pool will manage a collection of resources, ensuring that the pool size does not exceed a predefined limit. When a resource is requested, the Object Pool will either provide an existing idle resource or create a new one if no resources are available and the pool size limit has not been reached. The UML Diagram of this example is given below using Object Pool Design Pattern.

Example to Understand Advantages Object Pool Design Pattern in Java

Implementing Object Pool Design Pattern in Java

Step 1: Create a new directory to store all the class files of this project.

Step 2: Open VS Code and create a new project, called objectpool.

Step 3: In the project, create a new file called ObjectPool.java. This class represents the object pool.

Step 4: Import the following packages into ObjectPool.java:

Implementing Object Pool Design Pattern in Java

Step 5: Define the abstract class as follows:

Object Pool Design Pattern in Java

Step 6: Add the following fields to the abstract class:

Object Pool Design Pattern in Java with Examples

Step 7: Add the following function definition to the class:

What is a Object Pool Design Pattern?

This function definition is for an abstract function. This means that the function implementation will be added later in a different class.

Step 8: Add the initialise() function to the class:

UML Diagram of Object Pool Design Pattern in Java

This function creates the minimum number of objects.

Step 9: Add the following constructors:

Example to Understand Object Pool Design Pattern in Java

This function is responsible for creating an executor service and ensuring that the pool has the proper number of resources available.

Step 10: Add the remaining functions to the ObjectPool abstract class:

Implementing Object Pool Design Pattern in Java

  • The borrowObject() function is used to take an object from the pool and give it to a process.
  • The returnObject() function is invoked when the function (which borrowed the resource) would like to give it back.
  • The shutdown() function is used when the pool needs to be shut down.

Step 11: In the project, create a new file called ExportingProcess.java. Add the following lines of code to the file:

Object Pool Pattern in Java

This represents the resource that will be stored in the pool.

Step 12: In the project, create a new file called ExportingTask.java. Add the following lines of code to the file:

Object Pool Pattern in Java with Examples

This class is responsible for creating an object of type ObjectPool.

Step 13: In the project, create a new file called ObjectPoolDemo.java. This file will contain the main() function, as well as some other supplementary functions.

Step 14: Import the following packages into ObjectPoolDemo.java:

What is a Object Pool Pattern?

Step 15: Add the following fields to the abstract class:

UML Diagram of Object Pool Pattern in Java

Step 16: Add the following functions to the class

Example to Understand Object Pool Pattern in Java

These functions are responsible for the following:

  • setUp(): This function is supposed to set up the object pool.
  • tearDown(): This function is supposed to tear down the object pool once it is no longer required.
  • testObjectPool(): This function is used to test that the object pool works properly.

Step 17: Finally, write the main() function in the ObjectPoolDemo.java file:

Implementing Object Pool Pattern in Java

Step 18: Compile and execute the application. Ensure compilation is successful. Verify that the program works as expected.

Congratulations! You now know how to implement object pool patterns!

UML Diagram of Object Pool Design Pattern:

Now, let us see the Object Pool Design Pattern UML Diagram Components with our Example so that you can easily understand the UML Diagram.

UML Diagram of Object Pool Design Pattern

  1. ObjectPoolHandler: This handler class is supposed to manage the ObjectPool and facilitate the “borrowing” and “returning” of resources.
  2. ObjectPool: This class is responsible for containing the pool of objects.
  3. DriverClass: This class contains the main() function.
The Complete Example Code of the Object Pool Design Pattern in Java
ExportingProcess.java
public class ExportingProcess < private long processNo; public ExportingProcess(long processNo) < this.processNo = processNo; System.out.println("Object with process no: " + processNo + " was created!"); >public long getProcessNo() >
ExportingTask.java
public class ExportingTask implements Runnable < private ObjectPoolpool; private int threadNo; public ExportingTask(ObjectPool pool, int threadNo) < this.pool = pool; this.threadNo = threadNo; >@Override public void run() < ExportingProcess exportingProcess = pool.borrowObject(); System.out.println("Thread " + threadNo + ": Object " + exportingProcess.getProcessNo() + " was borrowed!"); pool.returnObject(exportingProcess); System.out.println("Thread " + threadNo + ": Object " + exportingProcess.getProcessNo() + " was returned!"); >>
ObjectPool.java
import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public abstract class ObjectPool  < private ConcurrentLinkedQueuepool; private ScheduledExecutorService executorService; protected abstract T createObject(); private void initialise (final int minObj) < pool = new ConcurrentLinkedQueue<>(); for (int i = 0; i < minObj; i++) pool.add(createObject()); >private ObjectPool (final int minObj) < initialise(minObj); >public ObjectPool (final int minObj, final int maxObj, final long interval) < executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleWithFixedDelay(new Runnable() < @Override public void run() < int size = pool.size(); if (size < minObj) for (int i = 0; i < minObj + size; i++) pool.add(createObject()); else if (size >maxObj) for (int i = 0; i < size - maxObj; i++) pool.poll(); >>, interval, interval, TimeUnit.SECONDS); > public T borrowObject() < T object; if ((object = pool.poll()) == null) object = createObject(); return object; >public void returnObject (T object) < if (object == null) return; this.pool.offer(object); >public void shutdown () < if (executorService != null) executorService.shutdown(); >>
ObjectPoolDemo.java
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; public class ObjectPoolDemo < private ObjectPoolpool; private AtomicLong processNo = new AtomicLong(0); public void setUp() < pool = new ObjectPool(4, 10, 5) < protected ExportingProcess createObject() < return new ExportingProcess(processNo.incrementAndGet()); >>; > public void tearDown () < pool.shutdown(); >public void testObjectPool() < ExecutorService executorService = Executors.newFixedThreadPool(8); executorService.execute(new ExportingTask(pool, 1)); executorService.execute(new ExportingTask(pool, 2)); executorService.execute(new ExportingTask(pool, 3)); executorService.execute(new ExportingTask(pool, 4)); executorService.execute(new ExportingTask(pool, 5)); executorService.execute(new ExportingTask(pool, 6)); executorService.execute(new ExportingTask(pool, 7)); executorService.execute(new ExportingTask(pool, 8)); executorService.shutdown(); try < executorService.awaitTermination(30, TimeUnit.SECONDS); >catch (InterruptedException e) < System.out.println(e.getMessage()); >> public static void main(String[] args) < ObjectPoolDemo opd = new ObjectPoolDemo(); opd.setUp(); opd.tearDown(); opd.testObjectPool(); >>
Advantages Object Pool Design Pattern in Java

Some of the advantages of using the object pool pattern are:

  • Improved Performance: The Object Pool pattern improves performance by eliminating the overhead of object creation and destruction. Reusing pre-initialized objects from the pool avoids the cost of repetitive object initialization and memory allocation, resulting in faster execution times.
  • Efficient Resource Management: By reusing objects from the pool, the Object Pool pattern optimizes resource utilization. It reduces the strain on system resources, such as memory or database connections, by reusing and sharing resources among multiple clients.
  • Object Lifetime Control: The Object Pool pattern allows for precise control over the lifetime of objects. Objects can be initialized and prepared in advance, ensuring they are in a consistent and ready-to-use state when acquired from the pool.
  • Scalability: The Object Pool pattern supports scalability by allowing the adjustment of the pool size. The number of objects in the pool can be dynamically increased or decreased based on system demands, ensuring efficient utilization of resources.
  • Thread Safety: Object pools can be designed to provide thread-safe access to objects, allowing multiple threads to acquire and release objects concurrently without causing race conditions or data corruption.
Disadvantages Object Pool Design Pattern in Java

Some of the disadvantages of using the object pool pattern are:

  • Increased Memory Usage: The Object Pool pattern may consume additional memory, especially when the pool size is fixed or when objects in the pool are not frequently reused. If objects in the pool remain idle for extended periods, memory usage may become inefficient.
  • Complexity and Maintenance: Implementing and maintaining an object pool can introduce complexity to the codebase. Managing object creation, allocation, and deallocation within the pool require careful synchronization and coordination, which may add overhead and make the codebase more intricate.
  • Limited Flexibility: Object pools may not be suitable for all types of objects or scenarios. Objects that are computationally expensive to create or that have complex initialization requirements may not benefit significantly from object pooling. Additionally, objects with variable lifetimes or those requiring frequent state changes may not be suitable for pooling.
  • Object Clean-up and Consistency: Ensuring that objects in the pool are properly cleaned and reset to a consistent state after being released can be challenging. Neglecting to clean objects adequately can lead to unexpected behavior or bugs when objects are acquired from the pool.
  • Pool Size Management: Determining the optimal pool size can be a challenge. If the pool size is too small, it may result in resource contention and decreased performance. On the other hand, if the pool size is too large, it may lead to unnecessary resource consumption and increased memory usage.

The Object Pool design pattern offers valuable advantages in efficient object reuse and resource management. Its benefits include improved performance, efficient resource utilization, precise control over object lifetimes, scalability, and thread safety. However, developers should consider potential disadvantages such as increased memory usage, complexity in implementation and maintenance, limited flexibility, object clean-up and consistency challenges, and the need for careful pool size management. By evaluating the specific requirements and trade-offs, developers can effectively utilize the Object Pool pattern to optimize performance, reduce resource consumption, and improve overall system efficiency.

In the next article, I am going to discuss Adapter Design Patterns in Java with Examples. Here, in this article, I try to explain Object Pool Design Pattern in Java with Examples. I hope you understood the need for and use of the Object Pool Design Pattern in Java.

Источник

Оцените статью