Object Pool Design Pattern
Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.
In the above
-
We create Singleton class to have object pool and create
private array to hold objects in it. -
Create acquireReusable()
and releaseResusable()
methods in the class. In addition to above methods, we can alsohave setMaxPoolSize()
method
The objects created in the object pool have lifecycle
Advantage of Object Pool Design Pattern:
-
Most effective when
creation ofobject is costly. - It boosts the performance of the application significantly.
- It can also provide the limit for the maximum number of objects that can be created.
- It manages the connections and provides a way to reuse and share them.
Object Pool Implementation:
To create Object Pool simple things that we need to do is:
- We need a pool(Collection) to store large/heavy objects.
-
An interface to get the object from
pool , returned the object and validation of the object.
Database connection object creation is
package com.codepumpkin.objectpool; import java.util.Enumeration; import java.util.Hashtable; public abstract class ObjectPool<T> { private long expirationTime; private Hashtable<T, Long> locked, unlocked; public ObjectPool() { expirationTime = 30000; // 30 seconds locked = new Hashtable<T, Long>(); unlocked = new Hashtable<T, Long>(); } protected abstract T create(); public abstract boolean validate(T o); public abstract void expire(T o); public synchronized T getObject() { long now = System.currentTimeMillis(); T t; if (unlocked.size() > 0) { Enumeration<T> e = unlocked.keys(); while (e.hasMoreElements()) { t = e.nextElement(); if ((now - unlocked.get(t)) > expirationTime) { // object has expired unlocked.remove(t); expire(t); t = null; } else { if (validate(t)) { unlocked.remove(t); locked.put(t, now); return (t); } else { // object failed validation unlocked.remove(t); expire(t); t = null; } } } } // no objects available, create a new one t = create(); locked.put(t, now); return (t); } public synchronized void releaseObject(T t) { locked.remove(t); unlocked.put(t, System.currentTimeMillis()); } }
Once we have our base ready we can easily extend it to create our actual connection pool class for
package com.codepumpkin.objectpool; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class JDBCConnectionPool extends ObjectPool<Connection> { private String url, usr, pwd; public JDBCConnectionPool(String driver, String url, String usr, String pwd) { super(); try { Class.forName(driver).newInstance(); } catch (Exception e) { e.printStackTrace(); } this.url = url; this.usr = usr; this.pwd = pwd; } @Override protected Connection create() { try { return (DriverManager.getConnection(url, usr, pwd)); } catch (SQLException e) { e.printStackTrace(); return (null); } } @Override public void expire(Connection o) { try { ((Connection) o).close(); } catch (SQLException e) { e.printStackTrace(); } } @Override public boolean validate(Connection o) { try { return (!((Connection) o).isClosed()); } catch (SQLException e) { e.printStackTrace(); return (false); } } }
Now we can use our JDBCConnectionPool class to obtain the
// Create the ConnectionPool: JDBCConnectionPool pool = new JDBCConnectionPool( "com.mysql.jdbc.Driver", "jdbc:mysql://localhost:3306/mydb", "root", "root"); // Get a connection: Connection connection = pool.getObject(); // Use the connection //... // Return the connection: pool.releaseObject(connection);
That's all for this topic. If you guys have any suggestions or queries, feel free to drop a comment. We would be happy to add that in our post. You can also contribute your articles by creating contributor account here.
Happy Learning 🙂
If you like the content on CodePumpkin and if you wish to do something for the community and the planet Earth, you can donate to our campaign for planting more trees at CodePumpkin Cauvery Calling Campaign.
We may not get time to plant a tree, but we can definitely donate ₹42 per Tree.
About the Author
Tags: Creational Design Patterns, Design Patterns, Object Pool Design Pattern
Comments and Queries
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:<pre><code class="java"> String foo = "bar"; </code></pre>For more information on supported HTML tags in disqus comment, click here.