Monday, February 9, 2009

DBCP Connection pooling – not so by default

Unlike in C#, one has to setup database connection pooling in Java. Not a big deal, as there are several ready-to-use libraries. We picked DBCP from apache commons. While unittests succeeded, stress tests were failing after exhausting all available TCP connections... To make long story short, the constructor we used to setup Object Pool did not pool connections: at first our code looked like this:

ObjectPool connPool = new GenericObjectPool(null, maxActive, GenericObjectPool.WHEN_EXHAUSTED_FAIL);

However, this only limits db connections but doesn’t reuse them. You can confirm this by either looking at the connection ids in my MySQL admin or simply running “netstat –a” and notice the ever-growing number of TCP connections – Windows holds on to TCP connection for a few minutes even after db connection is closed. The fix was rather simple: pass all required parameters:

ObjectPool connPool = new GenericObjectPool(null, maxActive,
GenericObjectPool.WHEN_EXHAUSTED_FAIL,
-1, //maxWait,
-1, //maxIdle,
false, //testOnBorrow,
false, // testOnReturn,
-1, //timeBetweenEvictionRunsMillis,
-1, //numTestsPerEvictionRun,
-1, //minEvictableIdleTimeMillis,
false); //testWhileIdle

C# wasn’t that bad after all, was it? ;)

No comments: