12

I've just started using BoneCP and pulled the sample JDBC code from the authors site.

I have a function called getConnection() that returns a connection here is a snippet:

    // setup the connection pool
BoneCPConfig config = new BoneCPConfig();
// Config goes here.
connectionPool = new BoneCP(config); // setup the connection pool

return connectionPool.getConnection(); // fetch a connection

Now, my questions: 1) Do I call connection.close() when I am finished using the connection that is returned from above function so it is returned to the pool OR does this close the connection completely? How do I return connection to pool?

2) How to cleanup the pool on application quit? Do I call connectionPool.shutdown() when i'm finishing up? And also, I read somewhere that I need to close all pooled connections individually? Is this true?

Thanks.

jim
  • 8,670
  • 15
  • 78
  • 149

2 Answers2

19

1. Always call connection.close() to return the connection to the pool (it won't be physically closed) when you're done with it.

2. Call connectionPool.shutDown() when you're completely done with the pool and not planning of reconnecting again.

rand0rn
  • 678
  • 2
  • 12
  • 29
wwadge
  • 3,506
  • 1
  • 19
  • 28
3
 Connection connection = dbPool.getConnection();

The Connection object gotten from the pool, is a wrapper class. It will maintain the underlying connection properly even in the Exception.

Even in the Connection related exceptions, for example, TERMINATE_ALL_CONNECTIONS, the BoneCP pool will properly close all the underlying connections.

In summary, BoneCP pool make the cache transparent. Client side only need follow the stand flow,

  1. request the connection (take the connection from pool, pool will decide whether to re-use/create one)
  2. request the PreparedStatement/CallableStatement (reuse the object from pool if it is enabled)
  3. execute the statements
  4. close statement, (release the statement object to the pool if it is enabled)
  5. close connection, (release the connection object to the pool)

When application stop, shutdown the pool to release all the cached connections.

boneCP.shutdown()
Shen liang
  • 1,385
  • 15
  • 15
  • I am wondering, if my server crashes and I have to restart, how do I clear out the connections that were not released since shutdown was never called? – Z2VvZ3Vp Feb 26 '14 at 18:07
  • BoneCP will hand them properly. To make it clear, BoneCP is more like an agent to manage the connections for you. you "lend" the connection from it, just need remember to "return" back. All other connection life cycle management tedious things will be taken care by BoneCP. – Shen liang Feb 28 '14 at 02:44
  • This is great to know, but it still feels strange to close the Connection object, which looks like an actual Connection object in a glance at BoneCP code. Any way I can see this? public Connection getConnection() throws SQLException {//compiled code} – Michael K Jun 20 '14 at 21:34