Use object pools

 

Overview

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. These 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

  1. Start the administrative console.

  2. Click Resources > Object Pools.

  3. Define the name of the object pool manager. This name can be up to 30 ASCII characters long.

  4. Assign the object pool manager a Java Naming and Directory Interface (JNDI) name.

  5. Provide a description of this object pool manager.

  6. Categorize the object pool manager.

 

Result

After you have completed these steps, applications can find the object pool manager by doing a JNDI lookup using the specified JNDI name.

 

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.

 

See also


Object pool managers
Object pool managers collection
Object pool service settings
Object pools: Resources for learning