How to work with Shutdown Hooks

A Shutdown Hook is a handler for the JVM shutdown process. Actions that need to be performed when the program terminates are defined in the implementation of a Thread object and passed to Runtime.getRuntime().addShutdownHook().

When using a shutdown hook, several nuances need to be considered:
  1. No guarantee of completion or execution: Hooks are called during normal program termination – when all user threads have finished or System.exit() is called. However, if System.halt() is called or if the program receives a SIGKILL signal, it will terminate immediately, potentially before or during the execution of hooks. A SIGTERM signal will trigger hooks, but the OS may not wait for them to complete and could abruptly terminate the process.
  2. System.exit(0) cannot be used in a hook: You can terminate with a non-zero code or use System.halt(). Returning a zero code after hooks have started will cause the program to hang.
  3. Hooks must be set before they start: Once the shutdown process has begun, calling addShutdownHook() will throw an exception.
  4. No execution order guarantees: If multiple hooks are registered, they may run in a random order and even in parallel, in separate threads. This behavior is hinted at by the form of the hook declaration – a Thread class.

For more details on the specifics of shutdown hooks, refer to the official questions and answers on the Shutdown Hooks API.