Question

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?

Was it helpful?

Solution

  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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top