Apache Common Pool – Object pool example


Advantage of using object pool is to improve performance of the application by saving time to create new object from other source for the same purpose. Object pool creates once and reuse for other subsequent operations on the same object. You can customize other configuration settings. Please visit this URL for more info: http://commons.apache.org/proper/commons-pool/api-1.6/index.html

Step:1 Add this Maven jar dependency in your POM.xml

<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.6</version>
</dependency>

Step:2 Create Factory  Class

import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.pool.BasePoolableObjectFactory;
import org.springframework.stereotype.Component;

/**
 * @author Rajiv Srivastava
 * Object pool factory
 */
//Extend BasePoolableObjectFactory class.
@Component
public class ObjectPoolFactory extends BasePoolableObjectFactory<ConnClient> {

 // for makeObject we'll simply return a new object e.g: connection object
 @Override
 public ConnClient makeObject() throws Exception {

 InputStream stream = null;
 // Create object code here for the first time. e.g: Create connection object from other integrated system component
 ConnClient connClient= new connClient();
 return connClient;
 }
}

Step:3 Create Object Pool class and usage

import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.PoolableObjectFactory;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.springframework.stereotype.Component;

/**
 * @author Rajiv Srivastava
 */

@Component
public class ObjectPoolConnection {

    private ObjectPool<ConnClient> pool;

	ConnClient obj = null;

	public ConnClient getConnClient(){

		PoolableObjectFactory<ConnClient> factory = new ObjectPoolFactory();
	    pool = new GenericObjectPool<ConnClient>(factory);

	        try {
	                try {
	                	if(obj==null){
	                		obj = (ConnClient)pool.borrowObject();
	                	}
	                } catch (Exception e) {
	                	obj=null;
	                	logger.error("failed to borrow object from Connection pool"+e.getMessage());
	                } finally {
	                    if (obj != null) {
	                        try {
								pool.returnObject(obj);
							} catch (Exception e) {
			                	logger.error("failed to return object from Connection"+e.getMessage());
							}
	                    }
	                }
	        } finally {
	            try {
					pool.close();
				} catch (Exception e) {
                	logger.error("failed to return pool"+e.getMessage());
				}
	        }
	    	return obj;
	}
}

Advertisements