Code Pumpkin

Object Pool Design Pattern

July 29, 2017
Posted by Pumpkin
Subscribe

Object pool design pattern is one of the Creational Design Pattern. In very simple term, this design pattern means To Reuse the objects which are very costly to create. Object pooling is creating objects of the class at the time of creation and put them into one common pool. Now whenever application needs object of that class instead of instantiating new object we will return the object from the object pool. Once the task is completed the object will be return back to the pool.

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.

Object Pool Design Pattern

In the above diagram the basic working of the object pool design pattern is explained. While creating object pool we follow below rules:

  • 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 have also have setMaxPoolSize() method to set the size of the pool.

The objects created in the object pool have lifecycle as  creation, validation and destroy. 

Advantage of Object Pool Design Pattern:

  • Most effective when creation of object 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 coastly as it involves database specific driver loading and many other things. So object pool is commonly used for creating pool of connections which can be directly served when requied. Which makes the execution of the application faster.

First we will create an abstract ObjectPool Class as below:


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 jdbc as below:


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 jdbc connection whenever required and once we are done with the usage we can simply return the obejct to pool as below:


    // 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 is all about object pool pattern. To check more such Design Pattern you can check our article on Design Patterns.

Happy Learning 🙂

Download Complete Java Program »

Tags: , ,


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.

Total Post : 80
Subscribe
Contribute Your Articles

Interview Experiences

Related Books

Like Us On Facebook

Alexa Page Rank