views:

326

answers:

2

I've been building a test application that works with a database that up until recently has been without a UI. I'm adding one now. Problem is, the JFrame is launched in another thread and I need my database connection to close when that thread closes (when the UI closes, I should say). How do I do this?

Also, what happens to the application's database connection (in this case an embedded database) if the application crashes or is forcefully closed? I hear that unclosed connections cause resource leaks. Anything I can do to clean up if this happens?

+3  A: 
  1. The WindowClosingEvent will be fired if a User attempts to close your JFrame. So in this method you can close your connection.
  2. Your DBMS uses a pool of connection. If you don't close your connections properly, this connection pool is filled with unused connection.
    It's bad if the pool is full and a new connection is needed. The application won't work. Either the user waits and tries it one more time (while he's waiting, one connection could be closed or killed) or the database is restarted manually so all connection are lost.
    The DBMS closes all unused connections after a predefined time. Which parameter does specify this time, you'll find it in your DBMS manual.

In addtion to your comment: You cannot assure that you have enough time to clean up your connections. Probably your application is killed by your sytem or whatever. So: Try to clean up your connection as soon as possible.
Unused connections can only be removed by the DBMS once you've lost the connection object.

furtelwart
Ah okay. But is there any way other than relying on the DBMS's timeout to clean up?
Daddy Warbox
See my answer, I added some information.
furtelwart
Is there a way to detect and clean up (or maybe just resume using?) unused connections (that the DBMS timeout doesn't get to clean up) on application restart from a previous instance?Or am I misunderstanding how this works?
Daddy Warbox
No, you cannot reuse your connection since your application was closed. Unused connection can only be removed by the DBMS.
furtelwart
Ok then. Thanks for the info.
Daddy Warbox
+4  A: 

You may add a shutdown hook to your runtime system. It's a thread which will be fired on closing the virtual machine. In the thread you can close all db connections and other critical resources.

Boris Pavlović
This won't solve the leaked connection problem, will it?
Daddy Warbox
No it won't. It will just give you an oportunity to close open connections manually or to tell the pool to shut down. You don't have a control over DBMS other then setting the timeout period.
Boris Pavlović