javajdbc

Java garbage collector on database connection


A question regarding garbage collector. If i have created database connection and performed some operations on databse and after that i have not used connection object for longer time can garbage collector frees my connection. I want this connection to be used later.

EDIT : just to confirm ,if i have created my connection is at context level of webapp then whats the case ?


Solution

  • If you keep a strong reference to a Connection object then garbage collector will never touch your object and database connection will remain. Just remember it cannot be used by multiple threads.

    On the other hand if you keep opened connection for too long some underlying resources (like TCP/IP socket) might get interrupted.

    If you loose the last reference to a connection (by overwriting it or setting to null) garbage collector will release all Java objects associated with the connection and the connection itself. But it will not release the underlying database connection, hence you must always explicitly call:

    connection.close();