How to close the database connection at the end of

2019-05-11 02:54发布

问题:

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?

回答1:

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 the TerminateProcess 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.