1

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ますか?

4

2 に答える 2

5

おそらく BasePoolableObjectFactory を拡張する独自の Factory を作成する必要があります。詳細については、http: //commons.apache.org/pool/examples.htmlを参照してください。

以下は、StringBuffer を作成する 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 は非常に興味深い例を成文化しました。The Java HotSpot: A Generic and Concurrent Object Poolで参照してください。

于 2012-05-31T18:02:34.683 に答える