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

前端 未结 2 1609
忘了有多久
忘了有多久 2021-01-13 04:55

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 w

2条回答
  •  感情败类
    2021-01-13 05:53

    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.

提交回复
热议问题