使用对象池
对象池帮助应用程序避免重复创建新的 Java 对象。大多数对象创建一次后即可反复使用。对象池支持共用正在等待复用的对象。
关于此任务
对象池并非用于共享 JDBC 连接或者 Java 消息服务 (JMS) 连接和会话。WebSphere Application Server 提供专门的机制,用于处理这些类型的对象。这些对象池的目的是共享应用程序定义的对象或基本开发工具箱类型。
要使用对象池,产品管理员必须使用管理控制台定义对象池管理器。可以在一个 Application Server 单元中创建多个对象池管理器。
注: 仅在 EJB 容器或 Web 容器中支持对象池管理器服务。不支持从 Java 2 Platform Enterprise Edition (J2EE) 应用程序客户机容器查找和使用配置的对象池管理器。
过程
结果
示例
下列代码说明了应用程序如何查找对象池管理器对象:
InitialContext ic = new InitialContext();
ObjectPoolManager opm = (ObjectPoolManager)ic.lookup("java:comp/env/pool");
当应用程序具有 ObjectPoolManager 时,它可以为其所要使用的类型的类高速缓存对象池。以下是一个示例:
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
}
当应用程序具有池时,应用程序可以使用它们,如以下示例所示:
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);
}
此示例表示使用对象池的基本模式。如果应用程序不返回对象,那么唯一的副作用是无法复用该对象。