Stunner
Stunner

Reputation: 1131

JDBC unclosed connections

If we forget to close Java JDBC connection (say oracle) in the code , would like to know will the connection stays at DB end forever (oracle) or the Oracle has any implementation at its end to auto release DB connections after some time?

try{
       ds.getConnection();
       //do some business logic

   }catch(Exception e){
       //handle exceptions

   }  finally{
           //let's say DB connection is NOT cosed..
      }

What happens to the open connection in the code above? Does the connection gets auto released at database side once the java program exits? I understand it is highly not recommended and bad practice to not close DB connections. I just want to know the implications and understand how oracle handles unclosed connections.

Upvotes: 0

Views: 578

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102872

Once the VM is terminated, whether more or less normally (all non-daemon threads end, System.exit is invoked, or a kill signal is received, such as hitting CTRL+C in the terminal), or abnormally (you trip over a powercord, or a terminate signal causes the kernel to just hard-exit your VM), all TCP/IP connections go away automatically, and with that, the connection is cleaned up.

But, until the VM exits, you get no guarantees. The behaviour is intentionally unspecified (as in, you must close them yourself. If you do not, no guarantees are provided), and what actually happens depends on the state of your computer (as it depends on gc runs and when those go depends on everything from which song is playing in your music player to the phase of the moon), and the JDBC driver being used.

You can use lint tools and IDE plugins to recognize that you aren't closing your connections. Also, your snippet is over 10 years out of date. The recommended and much simpler way to ensure your connection does not die on you is to use:

try (Connection con = ds.getConnection()) {
    // use 'con' here
} // no need for a catch or finally.

Or, use connection poolers (like HikariCP), along with an abstraction to make JDBC less annoying, such as JDBI or JOOQ.

Upvotes: 1

Related Questions