java.lang.Runtime
addShutdownHook
public void addShutdownHook(Thread hook)
-
Registers a new virtual-machine shutdown hook.
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
exit
(equivalently,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.
A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.
-
Example:
addShutdownHook(getShutdownHook());
protected void addShutdownHook(final Thread hook) {
getRuntime().addShutdownHook(hook);
}
private Thread getShutdownHook() {
return new Thread(new Runnable() {
}}