views:

120

answers:

2

As per my understanding, JDBC Connection Pooling (at a basic level) works this way:

  1. create connections during app initialization and put in a cache
  2. provide these cached connections on demand to the app
  3. a separate thread maintains the Connection Pool, performing activities like:
    • discard connections that have been used (closed)
    • create new connections and add to the cache to maintain a specific count of connections

But, whenever I hear the term "connection reuse" in a JDBC Connection Pooling discussion, I get confused. When does the connection reuse occurs?

Does it means that Connection Pool provides the same connection for two different database interactions (without closing it)? Or, is there a way to continue using a connection even after it gets closed after a DB call?

+4  A: 

Connection pooling works by re-using connections. Applications "borrow" a connection from the pool, then "return" it when finished. The connection is then handed out again to another part of the application, or even a different application.

This is perfectly safe as long as the same connection is not is use by two threads at the same time.

The key point with connection pooling is to avoid creating new connections where possible, since it's usually an expensive operation. Reusing connections is critical for performance.

skaffman
+3  A: 

The connection pool does not provide you with the actual Connection instance from the driver, but returns a wrapper. When you call 'close()' on a Connection instance from the pool, it will not close the driver's Connection, but instead just return the open connection to the pool so that it can be re-used (see skaffman's answer).

Tim Jansen
That depends on the specific type of connection pool you're using, e.g. `DataSource` or Commons DBCP-style. Lightweight pools can just return the raw `Connection`, and rely on the application code not calling `close()`.
skaffman
So, does this means that the JDBC connections in a pool necessarily rely on either Connection.commit() or Connection.setAutoCommit(true) - probably these calls are made in the over-ridden close() of the Connection wrapper.
Harprit