5

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?

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

5 Comments

but if i want for example 5 instance alway in execution? so when i borrow the object i have this 5 instance just ready
I think you can set minIdle to 5. then I think the pool will keep 5 instances in idle. I think you can borrow objects before to use in initialisation of your programme. for (int i=0,l=config.getMinIdle(); i<l; ++i) pool.returnObject(pool.borrowObject()); You can check pool.getNumIdle();
Note that if you want to create objects automatically when there are no idle objects left you can call BaseGenericObjectPool#setBlockWhenExhausted()
Maybe off topic, but how can I initialise pool with pre-created objects. I have a list of available addresses and each thread borrows one address for its work...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.