final PoolingDataSource poolingDataSource = new PoolingDataSource();
final Driver driver = ObjectUtilities.loadAndInstantiate(driverClass, PooledDatasourceHelper.class, Driver.class);
// As the name says, this is a generic pool; it returns basic Object-class objects.
final GenericObjectPool pool = new GenericObjectPool(null);
pool.setWhenExhaustedAction(whenExhaustedActionType);
// Tuning the connection pool
pool.setMaxActive(maxActiveConnection);
pool.setMaxIdle(maxIdleConnection);
pool.setMaxWait(waitTime);
pool.setMinIdle(minIdleConnection);
pool.setTestWhileIdle(testWhileIdle);
pool.setTestOnReturn(testOnReturn);
pool.setTestOnBorrow(testOnBorrow);
pool.setTestWhileIdle(testWhileIdle);
/*
ConnectionFactory creates connections on behalf of the pool.
Here, we use the DriverManagerConnectionFactory because that essentially
uses DriverManager as the source of connections.
*/
final Properties properties = new Properties();
properties.setProperty("user", databaseConnection.getUsername());
properties.setProperty("password", databaseConnection.getPassword());
final ConnectionFactory factory = new DriverConnectionFactory(driver, url, properties);
/*
Puts pool-specific wrappers on factory connections. For clarification:
"[PoolableConnection]Factory," not "Poolable[ConnectionFactory]."
*/
// This declaration is used implicitly.
//noinspection UnusedDeclaration
final PoolableConnectionFactory pcf = new PoolableConnectionFactory(factory, // ConnectionFactory
pool, // ObjectPool
null, // KeyedObjectPoolFactory
validQuery, // String (validation query)
false, // boolean (default to read-only?)
true // boolean (default to auto-commit statements?)
);
/*
initialize the pool to X connections
*/
logger.debug("Pool defaults to " + maxActiveConnection + " max active/" + maxIdleConnection + "max idle" + "with " + waitTime + "wait time"//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
+ " idle connections."); //$NON-NLS-1$
for (int i = 0; i < maxIdleConnection; ++i)
{
pool.addObject();
}
logger.debug("Pool now has " + pool.getNumActive() + " active/" + pool.getNumIdle() + " idle connections."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
/*
All of this is wrapped in a DataSource, which client code should
already know how to handle (since it's the same class of object
they'd fetch via the container's JNDI tree
*/