0% found this document useful (0 votes)
3 views6 pages

Object Pool Pattern

The Object Pool Design Pattern is a creational pattern that manages a pool of reusable objects to optimize resource usage, particularly when object creation is expensive. It addresses issues such as resource exhaustion and improves performance by reusing instances, as demonstrated through a DBConnection Pool example. However, it introduces complexities such as potential resource leakage and the need for thread safety in managing the pool.

Uploaded by

nimish sikri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views6 pages

Object Pool Pattern

The Object Pool Design Pattern is a creational pattern that manages a pool of reusable objects to optimize resource usage, particularly when object creation is expensive. It addresses issues such as resource exhaustion and improves performance by reusing instances, as demonstrated through a DBConnection Pool example. However, it introduces complexities such as potential resource leakage and the need for thread safety in managing the pool.

Uploaded by

nimish sikri
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Pool

Definition
The Problem (Ex: DBConnection Pool)
Code
Solution (Ex: DBConnection Pool)
Class Diagram
Implementation
Advantages
Disadvantages

Resources

Video → 43. LLD: Object Pool Design Pattern | Creational Design Patt
ern | Low Level Design

Definition
The Object Pool Design Pattern is a creational pattern that manages a set (pool) of reusable objects(like
DBConnection Objects). Instead of creating and destroying objects frequently, we reuse pre-created instances
from a pool.

Borrow an instance from the pool ➡ Use it and ➡ Return it to the pool

Object Pool Design Pattern is used when:


Object creation is expensive (CPU/memory).
The same type of object is needed repeatedly.
You want to limit the number of instances (e.g., database connections).

The Problem (Ex: DBConnection Pool)


Code
1 // Resource - Reusable Object
2 public class DBConnection {
3 Connection mySQLConnection;
4 public DBConnection() {
5 try {
6 mySQLConnection = DriverManager
7 .getConnection("jdbc:mysql://localhost:3306/DB",
"root", "root");
8 } catch (Exception e) {
9 [Link]();
10 }
11 }
12 }

1 // Object Pool
2 public class DBConnectionPoolManager {
3 List<DBConnection> freeConnections = new ArrayList<>();
4 List<DBConnection> inUseConnections = new ArrayList<>();
5 int INITIAL_POOL_SIZE = 3;
6 int MAX_POOL_SIZE = 6;
7
8 public DBConnectionPoolManager() {
9 for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
10 [Link](new DBConnection());
11 }
12 }
13
14 public DBConnection getDBConnection() {
15 DBConnection dbConnection = null;
16 if ([Link]() && [Link]() <
MAX_POOL_SIZE) {
17 [Link](new DBConnection());
18 [Link]("New DBConnection created and added to
freeConnections list.");
19 [Link]("freeConnections size: " +
[Link]());
20 [Link]("inUseConnections size: " +
[Link]());
21 } else if ([Link]() &&
[Link]() >= MAX_POOL_SIZE) {
22 [Link]("Pool is full. Cannot create new
DBConnection.");
23 return null;
24 }
25 dbConnection = [Link]([Link]() -
1);
26 [Link](dbConnection);
27 [Link]("DBConnection retrieved from
freeConnections list and added to inUseConnections list.");
28 [Link]("freeConnections size: " +
[Link]());
29 [Link]("inUseConnections size: " +
[Link]());
30 return dbConnection;
31 }
32
33 public void releaseDBConnection(DBConnection dbConnection) {
34 if (dbConnection != null) {
35 [Link](dbConnection);
36 [Link](dbConnection);
37 [Link]("DBConnection released from
inUseConnections list and added to freeConnections list.");
38 [Link]("freeConnections size: " +
[Link]());
39 [Link]("inUseConnections size: " +
[Link]());
40 } else {
41 [Link]("DBConnection is null. Cannot
release.");
42 }
43 }
44 }

1 // Client - Object Pool Problem Demo


2 public class Client {
3 public static void main(String[] args) {
4 // Creating a DBConnectionPoolManager
5 DBConnectionPoolManager poolManager = new
DBConnectionPoolManager();
6
7 // Creating 6 DBConnections (MAX_POOL_SIZE is 6)
8 DBConnection dbConnection1 = [Link]();
9 DBConnection dbConnection2 = [Link]();
10 DBConnection dbConnection3 = [Link]();
11 DBConnection dbConnection4 = [Link]();
12 DBConnection dbConnection5 = [Link]();
13 DBConnection dbConnection6 = [Link]();
14
15 // 7th DBConnection will not be created as the pool is full
(returns null)
16 DBConnection nullDBConnection = [Link]();
17 [Link](nullDBConnection == null ? "DBConnection is
null as POOL is full." : "DBConnection is not null");
18 [Link](dbConnection6); // Releasing a
DBConnection
19 DBConnection dbConnection = [Link](); //
Reusing the released DBConnection
20
21 // ****** Issues with this code ******
22 // What happens if another client tries to create a new
DBConnectionPoolManager?
23 DBConnectionPoolManager poolManager2 = new
DBConnectionPoolManager();
24 // more connections added to the pool that exceeds the
MAX_POOL_SIZE
25 [Link]("====== Same Instance? ======");
26 [Link](poolManager == poolManager2 ? "Same
instance of DBConnectionPoolManager" : "Different instances of " +
27 "DBConnectionPoolManager");
28
29 }
30 }

What's wrong with the above code? What happens if another client tries to create a new
DBConnectionPoolManager ?
More connections were added to the pool that exceed the MAX_POOL_SIZE .
Multiple connection list objects are being created to track connection usage.
The system will eventually lead to a memory leak.
Unreliable design.

Solution (Ex: DBConnection Pool)


This Object Pool Design Pattern is used in conjunction with the Singleton Design Pattern and requires
thread safety when acquiring and releasing resources.

Class Diagram

ObjectPool ( ObjectPool ): Maintains available and in-use objects.


ReusableObject ( DBConnection ): The object being pooled.
Client ( Client ): Uses and returns objects from the pool.

Implementation
1 // Resource - Reusable Object
2 public class DBConnection {
3 Connection mySQLConnection;
4
5 public DBConnection() {
6 try {
7 mySQLConnection = DriverManager
8 .getConnection("jdbc:mysql://localhost:3306/DB",
"root", "root");
9 } catch (Exception e) {
10 [Link]();
11 }
12 }
13 }

1 // Object Pool - Singleton Implementation


2 public class DBConnectionPoolManager {
3
4 // Singleton
5 private static DBConnectionPoolManager
dbConnectionPoolManagerInstance = null;
6
7 List<DBConnection> freeConnections = new ArrayList<>();
8 List<DBConnection> inUseConnections = new ArrayList<>();
9 int INITIAL_POOL_SIZE = 3;
10 int MAX_POOL_SIZE = 6;
11
12 // private constructor
13 private DBConnectionPoolManager() {
14 for (int i = 0; i < INITIAL_POOL_SIZE; i++) {
15 [Link](new DBConnection());
16 }
17 }
18
19 // Singleton - thread-safe double-checked locking
20 public static DBConnectionPoolManager getInstance() {
21 if (dbConnectionPoolManagerInstance == null) {
22 synchronized ([Link]) {
23 if (dbConnectionPoolManagerInstance == null) {
24 dbConnectionPoolManagerInstance = new
DBConnectionPoolManager();
25 }
26 }
27 }
28 return dbConnectionPoolManagerInstance;
29 }
30
31 // Thread-safe: Only one thread can access this method at a time
32 // and modify the freeConnections and inUseConnections lists
33 public synchronized DBConnection getDBConnection() {
34 DBConnection dbConnection = null;
35 if ([Link]() && [Link]() <
MAX_POOL_SIZE) {
36 [Link](new DBConnection());
37 [Link]("New DBConnection created and added to
freeConnections list.");
38 [Link]("freeConnections size: " +
[Link]());
39 [Link]("inUseConnections size: " +
[Link]());
40 } else if ([Link]() &&
[Link]() >= MAX_POOL_SIZE) {
41 [Link]("Pool is full. Cannot create new
DBConnection.");
42 return null;
43 }
44 dbConnection = [Link]([Link]() -
1);
45 [Link](dbConnection);
46 [Link]("DBConnection retrieved from
freeConnections list and added to inUseConnections list.");
47 [Link]("freeConnections size: " +
[Link]());
48 [Link]("inUseConnections size: " +
[Link]());
49 return dbConnection;
50 }
51
52 // Thread-safe: Only one thread can access this method at a time
53 // and modify the freeConnections and inUseConnections lists
54 public synchronized void releaseDBConnection(DBConnection
dbConnection) {
55 if (dbConnection != null) {
56 [Link](dbConnection);
57 [Link](dbConnection);
58 [Link]("DBConnection released from
inUseConnections list and added to freeConnections list.");
59 [Link]("freeConnections size: " +
[Link]());
60 [Link]("inUseConnections size: " +
[Link]());
61 } else {
62 [Link]("DBConnection is null. Cannot
release.");
63 }
64 }
65 }

1 // Client - Object Pool Solution Demo


2 public class Client {
3 public static void main(String[] args) {
4 [Link]("======= Object Pool Design Pattern
======");
5 // Creating a DBConnectionPoolManager
6 DBConnectionPoolManager poolManager =
[Link]();
7
8 // Creating 6 DBConnections (MAX_POOL_SIZE is 6)
9 DBConnection dbConnection1 = [Link]();
10 DBConnection dbConnection2 = [Link]();
11 DBConnection dbConnection3 = [Link]();
12 DBConnection dbConnection4 = [Link]();
13 DBConnection dbConnection5 = [Link]();
14 DBConnection dbConnection6 = [Link]();
15
16 // 7th DBConnection will not be created as the pool is full
(returns null)
17 DBConnection nullDBConnection = [Link]();
18 [Link](nullDBConnection == null ? "DBConnection is
null as POOL is full." : "DBConnection is not null");
19 [Link](dbConnection6); // Releasing a
DBConnection
20 DBConnection dbConnection7 = [Link](); //
Reusing the released DBConnection
21
22 // ******** Solution Demo **********
23 // What happens if another client tries to create a new
DBConnectionPoolManager?
24 DBConnectionPoolManager poolManager2 =
[Link]();
25 [Link]("====== Same Instance? ======");
26 [Link](poolManager == poolManager2 ? "Same
instance of DBConnectionPoolManager" : "Different instances of " +
27 "DBConnectionPoolManager");
28 }
29 }

Advantages
Reduce the overhead of creating and destroying the frequently required object (generally resource-intensive
objects).
Reduce the latency, as it uses the pre-initialized object.
Prevent resource exhaustion by managing the number of resource-intensive object creations.

Disadvantages
Resource leakage can happen if the object is not handled properly and is not returned to the pool.
Required more memory to manage the pool.
Pool management required thread safety, which is additional overhead.
Adds application complexity because of managing the pool.

You might also like