javaapache-commons-pool

Add object in pool with Apache Commons Pool 2


I want to create a pool of Object P with Apache Commons Pool 2. I create a P object with variable and method.

I create a PPool like this:

public class PPool extends GenericObjectPool<P>{

    /**
     * Constructor.
     * 
     * It uses the default configuration for pool provided by
     * apache-commons-pool2.
     * 
     * @param factory
     */
    public PPool(PooledObjectFactory<P> factory) {
        super(factory);
    }

    /**
     * 
     * 
     * @param factory
     * @param config
     */
    public PPool(PooledObjectFactory<P> factory,
            GenericObjectPoolConfig config) {
        super(factory, config);
    }
}

And after that I create a PFactory:

public class PhantomJsFactory extends BasePooledObjectFactory<Phantom> {

    @Override
    public P create() throws Exception {
        // TODO Auto-generated method stub
        return new P();
    }

    @Override
    public PooledObject<P> wrap(P phantomjs) {
        // TODO Auto-generated method stub
        return new DefaultPooledObject<P>(phantomjs);
    }

}

Now if I want to add, for example, 10 instances of P object how do I do that? I try with this:

        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxIdle(1);
        config.setMaxTotal(10);


        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        pool = new PPool(new PFactory(), config);

but now?


Solution

  • You don't need to add the instances. You supply the Factory of the P class. So the Pool will manage object lifecycle. If you obtain object, it will be created by the Pool if it is required. Therefore just borrow the object to use.

    P pObject = pool.borrowObject();
    

    See description GenericObjectPool.html#borrowObject()

    Please look at some test cases: TestGenericObjectPool.java