The Wayback Machine - https://web.archive.org/web/20240919120910/https://www.geeksforgeeks.org/object-pool-design-pattern/
Open In App

Object Pool Design Pattern

Last Updated : 15 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The Object Pool Design Pattern is a creational design pattern that manages a pool of reusable objects to minimize the overhead of creating and destroying objects. It maintains a collection of initialized objects and provides mechanisms for clients to efficiently borrow and return objects from the pool.

Object-Pool-Design-Patterns-copy

What is an Object Pool Design Pattern?

The Object Pool design pattern is a creational pattern that manages a pool of reusable objects, thus reducing the overhead of object creation and destruction. In this pattern, a pool of objects is created and maintained, and clients can borrow objects from the pool when they need them and return them to the pool when they’re done

  • An Object pool is a container that contains some amount of objects.
  • So, when an object is taken from the pool, it is not available in the pool until it is put back. 

What is the Object Pool Life Cycle?

The lifecycle of objects in an object pool involves the following stages:

  • Stage 1: Creation: Objects are initially created and added to the pool.
  • Stage 2: Borrowing: Clients request and borrow objects from the pool.
  • Stage 3: Usage: Clients use the borrowed objects for their tasks.
  • Stage 4: Returning: After usage, clients return the objects to the pool for reuse.
  • Stage 5: Rejection or Destruction: If the pool is full or objects are not used, they may be rejected or removed from the pool.

Components and UML Diagram of Object Pool Design Pattern

Object-Pool-Design-Pattern

Below are the main components of object pool design pattern:

  • Client : This is the class that uses an object of the PooledObject type.
  • ReuseablePool: The PooledObject class is the type that is expensive or slow to instantiate, or that has limited availability, so is to be held in the object pool.
  • ObjectPool : The Pool class is the most important class in the object pool design pattern. ObjectPool maintains a list of available objects and a collection of objects that have already been requested from the pool.

Real-World Example of Object Pool Design Pattern

Real-world analogy for the Object Pool design pattern could be a library or a bookstore.

  • Book Inventory:
    • Think of the library’s collection or the bookstore’s inventory as the pool of objects.
    • Each book represents an object that can be borrowed or used.
  • Borrowing Books:
    • When a library patron or a bookstore customer wants to borrow a book, they approach the librarian or the store clerk.
    • Similarly, in software, when a component needs an object, it requests it from the object pool.
  • Available Books:
    • The library or bookstore keeps track of available books that haven’t been borrowed yet.
    • These books are ready to be loaned out. Similarly, in the object pool, there are objects that are available for use.
  • Borrowing Process:
    • When a patron or a customer wants to borrow a book, they check out the book from the available collection.
    • This action is analogous to a component taking an object from the object pool.
  • Returning Books:
    • After reading or using the book, the patron or customer returns it to the library or bookstore.
    • Similarly, in software, when a component finishes using an object, it returns it to the object pool.
  • Book Condition:
    • The library or bookstore regularly checks the condition of the books, repairs any damages, and removes any books that are in poor condition from circulation.
    • This maintenance process is similar to the validation and cleanup procedures performed on objects in the object pool.
  • Maximum Book Inventory:
    • Both the library and the bookstore have a maximum limit on the number of books they can maintain due to space constraints or budget limitations.
    • Similarly, in software, object pools often have a maximum size to prevent resource exhaustion.

Example Implementation of Object Pool Design Pattern

Below is the example statement to understand object pool design pattern:

Let’s take the example of the database connections. It’s obviously that opening too many connections might affect the performance for several reasons: 

  • Creating a connection is an expensive operation.
  • When there are too many connections opened it takes longer to create a new one and the database server will become overloaded.

Here the object pool manages the connections and provide a way to reuse and share them. It can also limit the maximum number of objects that can be created. 

Let’s see component wise code:

1. Reusable Pool(PooledObject)

Java
import java.sql.Connection;
import java.sql.SQLException;

// This class represents the objects that are expensive to create or have limited availability
public class PooledObject {
    private Connection connection;

    public PooledObject(Connection connection) {
        this.connection = connection;
    }

    public Connection getConnection() {
        return connection;
    }

    public void close() {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public boolean isClosed() {
        try {
            return connection.isClosed();
        } catch (SQLException e) {
            e.printStackTrace();
            return true;
        }
    }
}

2. Object Pool

Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;

// ObjectPool class maintains a list of available objects and a collection of objects that have already been requested from the pool
public abstract class ObjectPool<T> {
    private long deadTime;
    private Hashtable<T, Long> lock, unlock;

    public ObjectPool() {
        deadTime = 50000; // 50 seconds
        lock = new Hashtable<>();
        unlock = new Hashtable<>();
    }

    abstract T create();

    abstract boolean validate(T o);

    abstract void dead(T o);

    public synchronized T takeOut() {
        long now = System.currentTimeMillis();
        T t;
        if (unlock.size() > 0) {
            Enumeration<T> e = unlock.keys();
            while (e.hasMoreElements()) {
                t = e.nextElement();
                if ((now - unlock.get(t)) > deadTime) {
                    unlock.remove(t);
                    dead(t);
                    t = null;
                } else {
                    if (validate(t)) {
                        unlock.remove(t);
                        lock.put(t, now);
                        return t;
                    } else {
                        unlock.remove(t);
                        dead(t);
                        t = null;
                    }
                }
            }
        }
        t = create();
        lock.put(t, now);
        return t;
    }

    public synchronized void takeIn(T t) {
        lock.remove(t);
        unlock.put(t, System.currentTimeMillis());
    }
}

3. Client

Java
import java.sql.Connection;

// Client class that uses an object of the PooledObject type
public class Client {
    public static void main(String[] args) {
        // Create the ConnectionPool:
        JDBCConnectionPool pool = new JDBCConnectionPool(
                "org.hsqldb.jdbcDriver", "jdbc:hsqldb: //localhost/mydb",
                "sa", "password");

        // Get a connection:
        Connection con = pool.takeOut();
        // Return the connection:
        pool.takeIn(con);
    }
}

Complete Code of the Above Example

Below is the complete code of the above example:

Java
// Java program to illustrate 
// Object Pool Design Pattern 
abstract class ObjectPool<T> { 
    long deadTime; 

    Hashtable<T, Long> lock, unlock; 

    ObjectPool() 
    { 
        deadTime = 50000; // 50 seconds 
        lock = new Hashtable<T, Long>(); 
        unlock = new Hashtable<T, Long>(); 
    } 

    abstract T create(); 

    abstract boolean validate(T o); 

    abstract void dead(T o); 

    synchronized T takeOut() 
    { 
        long now = System.currentTimeMillis(); 
        T t; 
        if (unlock.size() > 0) { 
            Enumeration<T> e = unlock.keys(); 
            while (e.hasMoreElements()) { 
                t = e.nextElement(); 
                if ((now - unlock.get(t)) > deadTime) { 
                    // object has dead
                    unlock.remove(t); 
                    dead(t); 
                    t = null; 
                } 
                else { 
                    if (validate(t)) { 
                        unlock.remove(t); 
                        lock.put(t, now); 
                        return (t); 
                    } 
                    else { 
                        // object failed validation 
                        unlock.remove(t); 
                        dead(t); 
                        t = null; 
                    } 
                } 
            } 
        } 
        // no objects available, create a new one 
        t = create(); 
        lock.put(t, now); 
        return (t); 
    } 
    synchronized void takeIn(T t) 
    { 
        lock.remove(t); 
        unlock.put(t, System.currentTimeMillis()); 
    } 
} 

// Three methods are abstract 
// and therefore must be implemented by the subclass 

class JDBCConnectionPool extends ObjectPool<Connection> { 
    String dsn, usr, pwd; 

    JDBCConnectionPool(String driver, String dsn, String usr, String pwd) 
    { 
        super(); 
        try { 
            Class.forName(driver).newInstance(); 
        } 
        catch (Exception e) { 
            e.printStackTrace(); 
        } 
        this.dsn = dsn; 
        this.usr = usr; 
        this.pwd = pwd; 
    } 

    Connection create() 
    { 
        try { 
            return (DriverManager.getConnection(dsn, usr, pwd)); 
        } 
        catch (SQLException e) { 
            e.printStackTrace(); 
            return (null); 
        } 
    } 

    void dead(Connection o) 
    { 
        try { 
            ((Connection)o).close(); 
        } 
        catch (SQLException e) { 
            e.printStackTrace(); 
        } 
    } 

    boolean validate(Connection o) 
    { 
        try { 
            return (!((Connection)o).isClosed()); 
        } 
        catch (SQLException e) { 
            e.printStackTrace(); 
            return (false); 
        } 
    } 
} 

class Main { 
    public static void main(String args[]) 
    { 
        // Create the ConnectionPool: 
        JDBCConnectionPool pool = new JDBCConnectionPool( 
            "org.hsqldb.jdbcDriver", "jdbc:hsqldb: //localhost/mydb", 
            "sa", "password"); 

        // Get a connection: 
        Connection con = pool.takeOut(); 
        // Return the connection: 
        pool.takeIn(con); 
    } 
} 

When to Use Object Pool Design Pattern?

Below is when to use object pool design pattern:

  • Expensive Object Creation: If creating instances of objects is resource-intensive, such as establishing database connections, network connections, or creating heavyweight objects, pooling can be beneficial. Pooling allows you to create these expensive objects once and reuse them multiple times.
  • Limited Resource Availability: When there’s a limited availability of resources, such as a limited number of database connections, pooling helps in efficiently managing those resources by reusing them rather than creating new ones beyond the limit.
  • Reducing Overhead: Object creation and destruction overhead can be significant in certain applications. By reusing objects from the pool, you can reduce the overhead associated with creating and destroying objects frequently.
  • Improving Performance: Pooling can lead to improved performance by avoiding the overhead of object creation and destruction and by reducing contention for limited resources.

When not to Use Object Pool Design Pattern?

Below is when not to use object pool design pattern:

  • Lightweight Objects: If objects are lightweight to create and destroy, and the overhead of object creation is negligible, then using an object pool might introduce unnecessary complexity without significant benefits.
  • No Resource Scarcity: If the system has abundant resources available and there’s no risk of resource exhaustion, implementing an object pool may not be necessary and could add unnecessary complexity.
  • Unpredictable Usage Patterns: If the usage pattern of objects is highly unpredictable, such that the objects are seldom reused or the pool size cannot be estimated effectively, then implementing an object pool might not be beneficial.
  • Maintenance Overhead: Object pools introduce additional complexity to manage the lifecycle of objects, such as handling object creation, validation, and destruction. If the maintenance overhead outweighs the benefits gained from pooling, it might not be worth implementing.
     


Similar Reads

Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Difference between Prototype Design Pattern and Flyweight Design Pattern
The major point in Prototype vs. Flyweight Design Pattern is that Prototype Design Pattern is a creational design pattern whereas Flyweight Design Pattern is a structural design pattern. In this post, we will look into this and more differences between the Prototype and Flyweight Design Patterns. Let us begin with a basic understanding of each of t
2 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
Difference Between Builder Design Pattern and Factory Design Pattern
Design patterns provide proven solutions to common problems in software design. The Builder and Factory patterns are two popular creational design patterns. The Builder pattern constructs complex objects step by step. In contrast, the Factory pattern creates objects without specifying their exact class. Both patterns streamline object creation but
7 min read
Why is Singleton Design Pattern is Considered an Anti-pattern?
Let us explore why the Singleton pattern, a popular way to ensure only one instance of a class exists, is now seen as problematic in software development. In this article, we will discuss drawbacks such as tight coupling between components, difficulty in unit testing, and issues with scalability in larger applications. Important Topics for Singleto
8 min read
Data Access Object(DAO) Design Pattern
Data Access Object Pattern or DAO pattern is a way of organizing code to handle the communication between your program and a database. It helps keep your code clean and separates the logic for interacting with data from the rest of your application. Important Topics for the Data Access Object(DAO) Design Pattern What is the Data Access Object(DOA)
15+ min read
Null Object Design Pattern
The Null Object Design Pattern is a behavioral design pattern that is used to provide a consistent way of handling null or non-existing objects. It is particularly useful in situations where you want to avoid explicit null checks and provide a default behavior for objects that may not exist. Important Topics for the Null Object Design Pattern What
7 min read
Null Object Method Design Pattern in Java
The Null Object Design Pattern is a behavioral design pattern that is used to provide a consistent way of handling null or non-existing objects. It is particularly useful in situations where you want to avoid explicit null checks and provide a default behavior for objects that may not exist. Important Topics for Null Object Method Design Pattern in
10 min read
What is a Memory Pool?
A memory pool, also known as a memory allocator or a memory management pool, is a software or hardware structure used to manage dynamic memory allocation in a computer program. It is a common technique used to efficiently allocate and deallocate memory for data structures and objects during program execution. It is a pre-allocated region of memory
11 min read
String Constant Pool in Java
In Java, Strings are the type of objects that can store the character of values. A string acts the same as an array of characters in Java. Memory allocation is not possible without String Constant Pool. In this article, we will learn about Java String Constant Pool. What is Java String Pool?A Java String Pool is a place in heap memory where all the
5 min read
Object Model | Object Oriented Analysis & Design
Object-Oriented Programming (OOP) is a fundamental paradigm in modern software development that has transformed the way we design, build, and maintain software systems. OOP is centered around the concept of objects, which are self-contained, reusable units that encapsulate both data and the operations that can be performed on that data. This approa
12 min read
Object Oriented System | Object Oriented Analysis & Design
Object Oriented System is a type of development model where Objects are used to specify different aspects of an Application. Everything including Data, information, processes, functions, and so on is considered an object in Object-Oriented System. Important Topics for the Object Oriented System Object Oriented SystemPhases of Object-Oriented Softwa
4 min read
Object Oriented Analysis in Object Oriented Analysis & Design
OOAD is a way of organizing and planning how to build computer programs by thinking in terms of ingredients (which we call objects). Just as you decide what each ingredient does in a recipe, OOAD helps us decide what each part of a computer program should do, how they should work together, and what makes each part special. Imagine you're cooking a
5 min read
Object Oriented Paradigm in Object Oriented Analysis & Design(OOAD)
There are two important steps in creating such software. Object-Oriented Analysis (OOA) and Object-Oriented Design (OOD). These steps are like the building blocks for creating software. Important topics for Object-Oriented Paradigm Object Oriented AnalysisObject-Oriented DesignHistorical ContextObject-Oriented Analysis (OOA)Object-Oriented Design (
6 min read
Composite Design Pattern | JavaScript Design Patterns
The Composite Design pattern is a way of organizing objects. It helps us handle different objects in a similar way when they are put together to create a structure with parts and wholes. These parts and wholes are like building blocks that can be split into smaller pieces and then put together to make a tree-like structure. The composite design pat
6 min read
Strategy Method Design Pattern | C++ Design Patterns
Strategy Pattern is a behavioral design pattern that defines a family of interchangeable algorithms and allows them to be used interchangeably within a context. This pattern enables the algorithm to be selected at runtime, providing flexibility and promoting code reusability. Important Topics for the Strategy Method in C++ Design Patterns Example o
4 min read
Memento Design Pattern | C++ Design Patterns
Memento Design Pattern is a behavioral design pattern that provides a mechanism for capturing an object's internal state and restoring it to that state at a later time. This pattern is useful when we need to implement features like undo/redo functionality or when we want to save and restore an object's state for various reasons. Important Topics fo
7 min read
Design Patterns Cheat Sheet - When to Use Which Design Pattern?
In system design, selecting the right design pattern is related to choosing the right tool for the job. It's essential for crafting scalable, maintainable, and efficient systems. Yet, among a lot of options, the decision can be difficult. This Design Patterns Cheat Sheet serves as a guide, helping you on the path toward optimal design pattern selec
7 min read
State Method Design Pattern | C++ Design Patterns
In software design, managing the behavior of an object according to its internal state is a common issue. The state pattern addresses this issue by allowing an object to alter its behavior every time its internal state changes. This pattern encapsulates each state in a separate class, which makes it easier to add new states and modify existing stat
7 min read
Template Method Design Pattern | C++ Design Patterns
Template Method Pattern introduces a template in a superclass that defines the steps of an algorithm. These steps may include both common tasks shared among subclasses and specific tasks that need customization. Subclasses then implement or override these steps to modify the algorithm according to their specific needs. Important Topics for Template
7 min read
Difference between Function Oriented Design and Object Oriented Design
Function-oriented design focuses on defining and organizing functions to perform specific tasks, starting with a high-level description and refining it step-by-step. It uses a top-down approach and often relies on structured analysis and data flow diagrams. On the other hand, object-oriented design emphasizes the data to be manipulated, organizing
4 min read
Object-Oriented Design (OOD) - System Design
Object-Oriented Design (OOD) is an important approach in system design, emphasizing modularity, reusability, and scalability. By encapsulating data and behavior into objects, OOD mirrors real-world systems, making software easier to understand and maintain. This method leverages principles like inheritance, polymorphism, and encapsulation, fosterin
12 min read
Pattern pattern() method in Java with Examples
The pattern() method of the Pattern class in Java is used to get the regular expression which is compiled to create this pattern. We use a regular expression to create the pattern and this method used to get the same source expression. Syntax: public String pattern() Parameters: This method does not accepts anything as parameter. Return Value: This
2 min read
Difference Between Bridge Pattern and Adapter Pattern
The Bridge Pattern and the Adapter Pattern are structural design patterns in object-oriented software development that primarily target the flexibility and reusability of a design. These two patterns have different roles and are used in different scenarios to solve specific design issues. Important Topics for Bridge Pattern vs Adapter Pattern What
5 min read
Difference between Strategy pattern and Command pattern
In software design, patterns provide reusable solutions to common problems. The Strategy and Command patterns are two important behavioral design patterns. The Strategy pattern allows the selection of an algorithm at runtime. The Command pattern encapsulates a request as an object. Understanding the differences between these patterns is crucial for
6 min read
Transfer Object Pattern in Java
It is used when we want to pass data with multiple attributes in one shot from client to server. Transfer Object is a simple POJO class having getter/setter methods and is serialized so that it can be transferred over the network. Server Side business class normally fetches data from the database and fills the POJO and sends it to the client or pas
4 min read
Collator compare(Object, Object) method in Java with Example
The compare() method of java.text.Collator class is used to compare the strength of two objects and it will return 0, positive and negative value as an output according to the result . Syntax: public int compare(Object o1, Object o2) Parameter: This method takes two objects between which comparison is going to take place.Return Value: if the first
2 min read
Difference Between State and Strategy Design Pattern in Java
It is important for a java developer to clearly understand the difference between State and Strategy Design Pattern in Core Java application in order to make the proper use of them. Though both State and Strategy design patterns have a similar structure, and both of them are based upon the Open closed design principle, represents 'O' from SOLID des
3 min read
Practice Tags :