Using object pools
An object pool helps an application avoid creating new Java objects repeatedly. Most objects can be created once, used and then reused. An object pool supports the pooling of objects waiting to be reused.
About this task
Object pools are not meant to be used for pooling JDBC connections or Java Message Service (JMS) connections and sessions. WebSphere Application Server provides specialized mechanisms for dealing with those types of objects. These object pools are intended for pooling application-defined objects or basic Developer Kit types.
To use an object pool, the product administrator must define an object pool manager using
the administrative console. Multiple object pool managers can be created in an Application Server
cell.
Note: The Object pool manager service is only supported from within the EJB
container or Web container. Looking up and using a configured object pool manager from a Java 2
Platform Enterprise Edition (J2EE) application client container is not supported.
Procedure
Results
Example
The following code illustrates how an application can find an object pool manager
object:
InitialContext ic = new InitialContext();
ObjectPoolManager opm = (ObjectPoolManager)ic.lookup("java:comp/env/pool");
When the application has an ObjectPoolManager, it can cache an object pool for classes of the
types it wants to use. The following is an
example:
ObjectPool arrayListPool = null;
ObjectPool vectorPool = null;
try
{
arrayListPool = opm.getPool(ArrayList.class);
vectorPool = opm.getPool(Vector.class);
}
catch(InstantiationException e)
{
// problem creating pool
}
catch(IllegalAccessException e)
{
// problem creating pool
}
When the application has the pools, the application can use them as in the following
example:
ArrayList list = null;
try
{
list = (ArrayList)arrayListPool.getObject();
list.clear(); // just in case
for(int i = 0; i < 10; ++i)
{
list.add("" + i);
}
// do what ever we need with the ArrayList
}
finally
{
if(list != null) arrayListPool.returnObject(list);
}
This example presents the basic pattern for using object pooling. If the application does not return the object, then the only adverse effect is that the object cannot be reused.