In a Java program, I have a singleton class that holds the database connection, which is used by the entire program.
How do I tell Java to close the connection when the program ends?
I can put a connection.close() statement at the end of main, but this will not be executed if the program ends unexpectedly, e.g, by an uncaught exception or "exit" call somewhere within the program. How do I tell Java to close the connection regardless of how the program ends?
You could use a VM shutdown hook if the method System.exit
might be called.
Runtime.getRuntime().addShutdownHook(new Thread(() -> closeDatabaseConnection()));
Shutdown hooks also will be called if the program exits normally:
The Java virtual machine shuts down in response to two kinds of events:
- The program exits normally, when the last non-daemon thread exits or when the
System.exit
method is invoked, or- The virtual machine is terminated in response to a user interrupt, such as typing
^C
, or a system-wide event, such as user logoff or system shutdown.
But there is no guarantee they will be run if something unexpected happens:
In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the
SIGKILL
signal on Unix or theTerminateProcess
call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With