Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does DBCP connection pool connection.close() return connection to pool

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

like image 661
Pratik Shelar Avatar asked Jan 29 '15 08:01

Pratik Shelar


People also ask

How do I return connection to connection pool?

close() along with normal Exception handling. If you are using a "standard" connection pool (i.e., you get the connection via a javax. sql. DataSource), you should call close() on the connection to return it to the pool.

Do we need to close connection in connection pool?

Yes, certainly you need to close the pooled connection as well. It's actually a wrapper around the actual connection. It wil under the covers release the actual connection back to the pool.

How does connection pooling works in spring boot?

Here's how Spring Boot automatically configures a connection pool datasource: Spring Boot will look for HikariCP on the classpath and use it by default when present. If HikariCP is not found on the classpath, then Spring Boot will pick up the Tomcat JDBC Connection Pool, if it's available.


1 Answers

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

like image 58
nos Avatar answered Oct 01 '22 10:10

nos