0

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

flixe
  • 626
  • 1
  • 11
  • 36

2 Answers2

0

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

saurabh2208
  • 72
  • 1
  • 1
  • 7
  • I tried out my application and it does not seem to work. How does the JVM know that my connection is taken from a connection pool, and that it should use `closeConnection()` instead of `connection.close()`? – flixe Sep 20 '17 at 09:27
-1

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.

user207421
  • 305,947
  • 44
  • 307
  • 483