I’ve got a Runnable which gets a connection from a connection pool as below and has 60 seconds to do something with the connection:
private static ConnectionPoolDataSource cpds; // MysqlConnectionPoolDataSource
public void run(){
while((System.currentTimeMillis()-created)<60000){
try(Connection conn = cpds.getPooledConnection().getConnection()){
//do something
}catch(SQLException sqle){}
}
}
When the thread dies after 60s, i’ve assumed the connection is returned to the pool and when a new thread is created the connection can be re-used. But when I list my network connections, the list keeps growing as more threads are created. Are connections created as above being returned to the pool correctly and if so how can I force the connections to be re-used ?
You are not actually using a connection pool. A
ConnectionPoolDataSourceisn’t intended to be used directly. It is intended as a (special)DataSourceforPooledConnectionobjects which are then kept in a connection pool by a (normal)DataSourceimplementation that provides connection pooling.A normal developer should not use a
ConnectionPoolDataSourcedirectly, it is intended for use with connection pools provided by Application Servers, or to be wrapped into general purposeDataSources that provide connection pooling.When a
Connectionis requested from the connection pool, it will checkout an existingPooledConnection(or request a new one from itsConnectionPoolDataSource), retrieve aConnectionand return that to the user. When the user closes theConnection, thePooledConnectionwill signal the connection pool that it is available again.In this case you are creating a
PooledConnection, retrieving aConnectionfrom it and then discarding thePooledConnection. This means that thePooledConnectiongets abandoned, and its physical connection to the database cannot be reused and will be closed/discarded when it is finally garbage collected (normally when the connection pool wants to close the physical connection, it will callclose()on thePooledConnection).You either need to use connection pooling as provided by your Application Server, or use a general purpose connection pool like DBCP, c3p0 or HikariCP.