Rakesh Juyal
Rakesh Juyal

Reputation: 36749

Will the sql connections automatically get closed if we close the JVM?

I created a test program which creates 20 threads and then these threads will open many sql connection. Lets say you are executing this program from eclipse and now if you will close eclipse. Will this close all opened sql connections? If not then what will happen to these? Will it show 100 opened connections on database side? If yes then what to do in this case?

Upvotes: 5

Views: 7420

Answers (2)

Lukas Eder
Lukas Eder

Reputation: 220842

The connections won't close as in calling java.sql.Connection.close(). Basically, the JVM that opened the connection can not keep the TCP/IP connections to the database alive. These will be shut down immediately. Hence, the "connection" will be shut down as well. The database, however, may not react immediately to this and keep its sessions alive for a while.

In Oracle, you can kill the sessions in the database directly, if you have sufficient privileges.

I guess, the behaviour is vendor-specific and/or configuration-specific. There is no general answer.

Upvotes: 9

AlexR
AlexR

Reputation: 115328

I believe that this depends on the database and the jdbc driver that you are using. I guess that in most cases the connections will be timed out and will be closed but it will not happen immediately. So, the better way is to close connection explicitly. Here are the usual techniques:

  1. do it in finally block that wraps the db connection session.
  2. Just in case write finalize() method and close connection there. It will help to close connection when something is going wrong and the object that connected to DB is going to be garbage collected before the connection is closed.
  3. You can create shutdown hook that is invoked automatically by JVM when process is going down. This helps in most cases when you are killing JVM from outside (except kill -9 in unix)

BTW I believe that in your case you do not need many connections to DB. Try to reuse one from all your 100 threads.

Upvotes: 0

Related Questions