Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using BoneCP: Handling connections from the pool

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?

like image 967
pgsandstrom Avatar asked Aug 04 '11 16:08

pgsandstrom


People also ask

When should you not use connection pooling?

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.

What are some of the main issues with using connection pools?

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.

Should I close a pooled DB connection?

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.

What is the use of connection 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.


1 Answers

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

like image 140
MJB Avatar answered Oct 13 '22 00:10

MJB