Java Connection Pool and try-with statements: Is Connection actually closed or returned to pool?

943 views Asked by At

I have a jdbc connection pool using the KeyedObjectPool class and i use it via the implemented methods openConnection() and closeConnection(). closeConnection() normally just returns the connection to the pool and closes it only if it has been used to often before. Therefore it uses ConnectionPool.returnObject() which does NOT close the connection object (see here).

class ConnectionPool
{

public openConnection(...)
{
   ...
}

public closeConnection()
{
   ...
}
}

However, if i use the connection pool like this:

    try (Connection connection = sConnectionPool.openConnection(JdbcCredentials);)
    {
        doSomething();
    }
    catch (Exception e) 
    {
       ...
    }

Is the connection object using try-with only returned to the pool or actually closed with connection.close() (which i don't want to happen because it would make my pool useless)?

2

There are 2 answers

3
user207421 On

close() on a pooled connection returns it to the pool, regardless of whether that was caused by the try or your own code.

Otherwise it wouldn't be reusable, so it wouldn't be a connection pool.

1
saurabh2208 On

It's actually a wrapper around the actual connection. It will, under the covers, release the actual connection back to the pool. It's further up to the pool to decide whether the actual connection will actually be closed or be reused for a new getConnection().