Shutdown hooks in Java¶
In Java, a shutdown hook is a thread that is initialized but not started, which the Java Virtual Machine (JVM) registers to execute during shutdown.^[600-developer__java__java-base__java-Runtime-Number.md] These hooks allow applications to perform specific cleanup tasks—such as releasing resources or saving state—when the JVM terminates, whether due to a normal exit or an abrupt interruption.
Registration and Removal¶
Shutdown hooks are managed via the Runtime class, which can be accessed using Runtime.getRuntime().^[600-developer__java__java-base__java-Runtime-Number.md] The addShutdownHook(Thread) method allows an application to register a specific thread for execution during the shutdown sequence.^[600-developer__java__java-base__java-Runtime-Number.md]
It is possible to register multiple Shutdown hooks; they are typically executed in an unspecified order during the shutdown process^[600-developer__java__java-base__java-Runtime-Number.md], though the order of registration may influence the sequence in some environments. If a hook is no longer needed, it can be removed using the removeShutdownHook(Thread) method^[600-developer__java__java-base__java-Runtime-Number.md].
Behavior and Limitations¶
Shutdown hooks are designed to run when the JVM shuts down normally (e.g., when the last non-daemon thread exits or System.exit() is called).^[600-developer__java__java-base__java-Runtime-Number.md] However, they are not invoked if the JVM is halted abruptly using the Runtime.halt(int) method^[600-developer__java__java-base__java-Runtime-Number.md].
The halt() method forcibly terminates the running Java virtual machine immediately, bypassing the normal shutdown sequence and preventing any registered Shutdown hooks from running^[600-developer__java__java-base__java-Runtime-Number.md].
Related Concepts¶
- [[Java Runtime]]
- [[Multithreading]]
- [[Resource management]]
Sources¶
^[600-developer__java__java-base__java-Runtime-Number.md]