Search code examples
javamemory-managementconnection-poolingapache-commonsapache-commons-dbcp

How do I properly destroy an Apache Commons DBCP Pool in Java?


I would like to use a PoolingDataSource as my connection pool (API at: http://commons.apache.org/dbcp/apidocs/org/apache/commons/dbcp/PoolingDataSource.html), but I don't know what to do with the pool when I no longer need it. What if I want to connect to a new database and don't need the connections in the old pool anymore? There is no close method on the pool.


Solution

  • You don't necessarily need to kill this pool to create a new one.

    You can manage the connections in it using the maxIdle, timeBetweenEvictionRunsMillis and minEvictableIdleTimeMillis parameters (see here) to ensure idle connections get closed in a reasonable time.

    Or you can configure a GenericObjectPool with those parameters programatically and use when creating your PoolingDataSource. That has a close() method if you want to force it.