1

我已将 commons-pooling-1.6.jar 添加到我的类路径中,并尝试实例化 aStackObjectPool并且每次都失败:

// 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 的一些开源替代方案是什么?否则,我如何实例化 a StackObjectPool

4

2 回答 2

5

您需要编写自己的工厂,可能会扩展 BasePoolableObjectFactory。有关更多信息,请参见此处:http: //commons.apache.org/pool/examples.html

下面是一个创建 StringBuffers 的 PoolableObjectFactory 实现:

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())
于 2012-05-31T17:43:33.117 回答
1

大多数库的输入都集中在对象工厂上。这告诉池在需要时如何创建新对象。例如,对于一个连接池,所有这些都连接到具有相同配置的同一个数据库,例如userpasswordurldriver

需要创建一个具体的工厂扩展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);
}

Swaranga Sarma 编写了一个非常有趣的例子。在Java HotSpot:通用和并发对象池中查看它

于 2012-05-31T18:02:34.683 回答