Apache Commons Pool 1 -> 2: Recalling Hung or Inactive Connection Objects to the Pool

1.2k Views Asked by At

Currently I am using Apache Commons Pool 1.6 to manage a GenericKeyedObjectPool pool of connections. I have seen threads both throwing exceptions and hanging indefinitely both of which lead to the borrowed connections being leaked from the pool. I have corrected the leaking of connections in the case of exceptions being thrown using returnObject() but ideally I would like some way for the pool to manage this and retrieve hung or leaked connections.

From my investigation so far Commons Pool 1.x does not provide this functionality and that Commons Pool 2.x does but so far I cannot find how this is done.

How are borrowed connections pulled back into the pool when hung or leaked using Apache Commons Pool 2?

Thanks

1

There are 1 best solutions below

0
On

Apache commons pools2 has a AbandonedConfig, that helps abandon the borrowed objects if they are not returned with a duration defined by 'removeAbandonedTimeout'.
Example :

        AbandonedConfig abandonedConfig = new AbandonedConfig();
        abandonedConfig.setRemoveAbandonedTimeout(evictAbandonedTime); // in seconds
        abandonedConfig.setRemoveAbandonedOnBorrow(true); // on borrow, test when pool is starving
        abandonedConfig.setRemoveAbandonedOnMaintenance(true); // and test pool when evicting
        pool.setAbandonedConfig(abandonedConfig);

However, AbandonedConfig is applicable for ONLY GenericObjectPool and NOT GenericKeyedObjectPoolConfig.

The only way, and probably crude way, to achieve this in commons pool2 is, to use multiple GenericObjectPool instances (with only one object in its pool) under a single key in GenericKeyedObjectPool and set the GenericObjectPool with AbandonedConfig.

The thing I hate about this solution is to do a borrow twice, but on the bright side the second borrow is never going to take time.