Generic Object pooling API with several implementations.
The org.apache.commons.pool2
package defines a simple
interface for a pool of object instances, and a handful of base
classes that may be useful when creating pool implementations.
The API supports pooling of unique objects which can be requested
via a key as well as pools where all objects are equivalent.
The org.apache.commons.pool2.impl
package contains
several pool implementations.
{@link org.apache.commons.pool2.impl.GenericObjectPool
GenericObjectPool} has many configuration options and can support
a limited set of objects such as would be useful in a database
connection pool.
{@link org.apache.commons.pool2.impl.SoftReferenceObjectPool
SoftReferenceObjectPool} has no limit on the number of objects in the
pool, but the garbage collector can remove idle objects from the pool
as needed. There is also a keyed version of
{@link org.apache.commons.pool2.impl.GenericObjectPool
GenericObjectPool},
{@link org.apache.commons.pool2.impl.GenericKeyedObjectPool
GenericKeyedObjectPool}
Here is a simple example of pooling HashMap
instances.
First create an {@link org.apache.commons.pool2.PoolableObjectFactory
PoolableObjectFactory}
public class HashMapFactory extends {@link org.apache.commons.pool2.BasePoolableObjectFactory BasePoolableObjectFactory}<Map<Object,Object>> { /** * Creates an instance that can be returned by the pool. * @return an instance that can be returned by the pool. */ public Map<Object,Object> makeObject() throws Exception { return new HashMap<Object,Object>(); } /** * Uninitialize an instance to be returned to the pool. * @param obj the instance to be passivated */ public void passivateObject(Map<Object,Object> obj) throws Exception { obj.clear(); } }
A class that makes frequent use of a Map could then use a pool as shown below:
public class Foo { private {@link org.apache.commons.pool2.ObjectPool ObjectPool<Map<Object,Object>>} pool; public Foo() { {@link org.apache.commons.pool2.PoolableObjectFactory PoolableObjectFactory<Map<Object,Object>>} factory = new HashMapFactory(); pool = new {@link org.apache.commons.pool2.impl.GenericObjectPool GenericObjectPool}<Map<Object,Object>>(factory); } public doSomething() { ... Map<Object,Object> map = null; try { map = pool.borrowObject(); // use map ... } finally { if (map != null) { pool.returnObject(map); } } ... } }
The above example shows how one would use an {@link org.apache.commons.pool2.ObjectPool ObjectPool}. The other supplied implementations or another special purpose pool would be used similarly.