6

Using BasicDataSource from DBCP if we do a getConnection() and in the finally block we close the connection does it really return the connection to the pool or does it close the connection. The snippet code I am checking is this

try {
        Connection conn1 = getJdbcTemplate().getDataSource()
                .getConnection();
        //Some code to call stored proc 

    } catch (SQLException sqlEx) {
        throw sqlEx;
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException ex1) {
            throw ex1;
        }

    }

I was checking the source code of BasicDataSource and I reached this wrapper class for the connection.

private class PoolGuardConnectionWrapper extends DelegatingConnection {

    private Connection delegate;

    PoolGuardConnectionWrapper(Connection delegate) {
        super(delegate);
        this.delegate = delegate;
    }

    public void close() throws SQLException {
        if (delegate != null) {
            this.delegate.close();
            this.delegate = null;
            super.setDelegate(null);
        }
    }

The delegate object if of type java.sql.Connection. The wrapper code calls the close method of the delegate which will close the collection rather than returning the connection to pool. Is this a known issue with DBCP or am I reading the source code incorrectly please let me know.

Thanks

Pratik Shelar
  • 3,154
  • 7
  • 31
  • 51
  • You are closing the connection...Why would you do that? – SMA Jan 29 '15 at 08:26
  • If I don't close the connection the pool throws an error after the maxActive Limit is reached. I am just checking this because I read that if we close a connection in connectionpool, the connection wrapper instead of closing the connection puts it back in the pool. But from source code I cannot infer the same – Pratik Shelar Jan 29 '15 at 08:36

1 Answers1

7

You'll end up calling PoolableConnection.close(), which returns it to the pool.

nos
  • 223,662
  • 58
  • 417
  • 506
  • Thanks I messed up while reading the source code !! Now it makes sense – Pratik Shelar Jan 30 '15 at 10:09
  • 1
    as `Connection extends AutoCloseable`, you can use a `try-with-resource` block, that will call `conn.close()` when exiting the `try (Connection conn = ... ) { }` block, which will indeed return the connection to the pool, but *not* actually close it between the pool and the db. – Julien Nov 22 '19 at 13:39