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, orThe 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.
Thus, a shutdown hook is a initialized and unstarted thread that gets executed when a JVM shutdown occurs.
Shutdown hook registered
Before calling exit
Inside Shutdown hook
Shutdown hook thread sleeping for 2 seconds
Shutdown hook thread waking up
Shutdown hook thread terminating
Running Shutdown Hook
- your program had created many temporary files in filesystem you want to delete it;
- you need to send a distress signal to another process/machine before terminating;
- execute any clean-up actions, logging or after-error actions on unexpected behaviours.