Frage

I've added commons-pooling-1.6.jar to my classpath and trying to instantiate a StackObjectPool and am failing at every turn:

// 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);

Is this a deprecated API altogether? If so, what are some open source alternatives to Commons Pooling? Else, how do I instantiate a StackObjectPool?

War es hilfreich?

Lösung

You need to write your own Factory possibly extending BasePoolableObjectFactory. See here for more information: http://commons.apache.org/pool/examples.html

Below is a PoolableObjectFactory implementation that creates 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 
}

Then use it as follows:

new StackObjectPool<StringBuffer>(new StringBufferFactory())

Andere Tipps

Most libraries have input focuses on an object factory. This tells to the pool how create a new object when this is needed. E.g. for a pool of connections, all these are connected to the same database with the same configuration, like user, password, url, driver.

Need to create a concrete factory extending BasePoolableObjectFactory class and write the method makeObject, as shown in the following example.

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 has codified a very interesting example. See it at The Java HotSpot: A Generic and Concurrent Object Pool

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top