Question

I am trying to use apache commons pool to create a pool of 'objects'. Since I already have an object factory which takes a string type argument and create a right type of object I want to use this factory.

But the problem is that none of the signatures of generic pool object allow me to pass a factory which takes arguments.

//This is a wrapper class that holds an Object pool
Class INService {

    private ObjectPool<INConnection> pool_ = null;

    /**
     * Constructs an instance of INService, given a pool size 
     * and a class which implements INHandler interface.
     * @param poolSize - size of the service pool 
     * @param c - the class which handles the INHandler service interface.
     */
    public INService(int poolSize, String objectType) {

        pool_ = new GenericObjectPool<INConnection>(factory, Objecttype); // won't compile.
    }
    ...
}

The PoolableObjectfactory interface defines methods like makeObject, destroyObject, validateObject, activateObject and passivateObject. But no makeObject() method which takes parameters.

It seems that the only way I can do this is to write multiple factory classes for each type of object and write an if-else stuff, like:

    public INService(int poolSize, String objectType) {

        if (objectType.equals("scap")
            pool_ = new GenericObjectPool<INConnection>(scapFactory);
        else if (objectType.equals("ucip")
            pool_ = new GenericObjectPool<INConnection>(ucipFactory);
        ...
    }

Or, is there any elegant way, instead of duplicating/creating several factory classes just for this sake?

Was it helpful?

Solution

You should read up on the KeyedObjectPool<K,V> interface which can also be found in commons-pool.

From its javadoc:

A keyed pool pools instances of multiple types. Each type may be accessed using an arbitrary key.

You could then implement a KeyedPoolableObjectFactory<K,V> to make instances based on the key parameter, it has the makeObject(K key) function you are looking for.

PS: It appears you haven't marked any answers to your questions as "accepted", you might want to work on that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top