JDBC Connection Pooling: Connection Reuse?

后端 未结 4 1969
名媛妹妹
名媛妹妹 2020-12-28 08:22

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. pr
相关标签:
4条回答
  • 2020-12-28 08:44

    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).

    0 讨论(0)
  • 2020-12-28 08:46

    Connection pooling reuses connections. Here is how apache dbcp works underline.

    Connection poolableConnection= apacheDbcpDataSource.getConnection();
    

    Apache DBCP implementation returns connection wrapper which is of type PoolableConnection.

    poolableConnection.close();
    

    PoolableConnection.close() inspects if actual underlying connection is closed or not, if not then it returns this PoolableConnection instance into connection pool (GenericObjectPool in this case).

    if (!isUnderlyingConectionClosed) {
                // Normal close: underlying connection is still open, so we
                // simply need to return this proxy to the pool
                try {
                    genericObjectPool.returnObject(this); //this is PoolableConnection instance in this case
    ....
                  }
    
    0 讨论(0)
  • My understanding is the same as stated above and, thanks to a bug, I have evidence that it's correct. In the application I work with there was a bug, an SQL command with an invalid column name. On execution an exception is thrown. If the connection is closed then the next time a connection is gotten and used, with correct SQL this time, an exception is thrown again and the error message is the same as the first time though the incorrect column name doesn't even appear in the second SQL. So the connection is obviously being reused. If the connection is not closed after the first exception is thrown (because of the bad column name) then the next time a connection is used everything works just fine. Presumably this is because the first connection hasn't been returned to the pool for reuse. (This bug is occurring with Jave 1.6_30 and a connection to a MySQL database.)

    0 讨论(0)
  • 2020-12-28 08:56

    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.

    0 讨论(0)
提交回复
热议问题