I have just started using BoneCP and this is my first time using a connection pool. I'm somewhat confused as to how I am supposed to use it. Currently I am saving the BoneCP-object as a static variable, and thus I can use it between different connections.
When I'm done with the connection, I close it with connection.close()
.
Should I do this, or should I not close it to enable it to be reused by the pool?
This is my current implementation to get a connection:
private static BoneCP connectionPool;
public Connection getConnection() throws SQLException {
if (connectionPool == null) {
initPool();
}
return connectionPool.getConnection();
}
private void initPool() throws SQLException {
BoneCPConfig config = new BoneCPConfig();
config.setJdbcUrl(DB_URL);
config.setUsername(DB_USERNAME);
config.setPassword(DB_PASSWORD);
config.setMinConnectionsPerPartition(5);
config.setMaxConnectionsPerPartition(10);
config.setPartitionCount(1);
connectionPool = new BoneCP(config);
}
Does this seem correct or have I misunderstood how I am supposed to use BoneCP?
You reuse a prior database connection, in a new context to avoid the cost of setting up a new database connection for each request. The primary reason to avoid using database connections is that you're application's approach to solving problems isn't structured to accommodate a database connection pool.
One of the most common issues undermining connection pool benefits is the fact that pooled connections can end up being stale. This most often happens due to inactive connections being timed out by network devices between the JVM and the database. As a result, there will be stale connections in the pool.
Yes, certainly you need to close the pooled connection as well. It's actually a wrapper around the actual connection. It wil under the covers release the actual connection back to the pool.
Using connection pools helps to both alleviate connection management overhead and decrease development tasks for data access. Each time an application attempts to access a backend store (such as a database), it requires resources to create, maintain, and release a connection to that datastore.
Other than making your private static final and changing the init to a static block (or alternaitvely making your getConnection synchronized), you are ok.
You are correct you MUST do connection.close() to return to the pool. When your app shuts down, shut down the connection pool
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With