JDBC Connection Pooling: Connection Reuse?

haps10 picture haps10 · Jun 21, 2010 · Viewed 7.5k times · Source

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?

Answer

skaffman picture skaffman · Jun 21, 2010

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.