You can add a shutdown hook by using Runtime.getRuntime().addShutdownHook(). Such a shutdown hook is run by the JVM, once the JVM' process terminates. However, note that this is not always the case. A JVM might get killed before it gets the chance to trigger its shutdown hooks. This is mentioned in the javadoc:
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.
You can use a shut down hook as follows:
Runtime.getRuntime().addShutdownHook(
new Thread("app-shutdown-hook") {
@Override
public void run() {
System.out.println("bye");
}
});
You can and should also deregister a shut down hook once it is no longer required. Otherwise, the JVM can never garbage collect the hook.