我已经将commons-pooling-1.6.jar添加到我的类路径并试图实例化StackObjectPool
并且每次都失败了:
// Deprecated.
ObjectPool<T> oPool = new StackObjectPool<T>();
// Error: Cannot instantiate the type BasePoolableObjectFactory<T>.
PoolableObjectFactory<T> oFact = new BasePoolableObjectFactory<T>();
ObjectPool<T> oPool = new StackObjectPool<T>(oFact);
这是一个弃用的API吗?如果是这样,Commons Pooling的一些开源替代品是什么?否则,我如何实例化StackObjectPool
?
答案 0 :(得分:5)
您需要编写自己的工厂,可能会扩展BasePoolableObjectFactory。有关详细信息,请参阅此处:http://commons.apache.org/pool/examples.html
下面是一个PoolableObjectFactory实现,它创建了StringBuffers:
import org.apache.commons.pool.BasePoolableObjectFactory;
public class StringBufferFactory extends BasePoolableObjectFactory<StringBuffer> {
// for makeObject we'll simply return a new buffer
public StringBuffer makeObject() {
return new StringBuffer();
}
// when an object is returned to the pool,
// we'll clear it out
public void passivateObject(StringBuffer buf) {
buf.setLength(0);
}
// for all other methods, the no-op
// implementation in BasePoolableObjectFactory
// will suffice
}
然后按如下方式使用:
new StackObjectPool<StringBuffer>(new StringBufferFactory())
答案 1 :(得分:1)
大多数图书馆的输入重点是对象工厂。这告诉池如何在需要时创建新对象。例如。对于连接池,所有这些都使用相同配置连接到同一数据库,例如 user , password , url < / em>,驱动程序。
需要创建一个扩展BasePoolableObjectFactory
类的具体工厂并编写方法makeObject
,如下例所示。
static class MyObject {
private String config;
public MyObject(String config) {
this.config = config;
}
}
static class MyFactory extends BasePoolableObjectFactory<MyObject> {
public String config;
public MyFactory(String config) {
this.config = config;
}
@Override
public MyObject makeObject() throws Exception {
return new MyObject(config);
}
}
public static void main(String[] args) {
MyFactory factory = new MyFactory("config parameters");
StackObjectPool<MyObject> pool = new StackObjectPool<>(factory);
}
斯瓦兰加萨玛已经编纂了一个非常有趣的例子。请参阅The Java HotSpot: A Generic and Concurrent Object Pool