Understanding java.lang.Runtime.addShutdownHook for JVM Graceful Shutdown
This article explains the Java Runtime addShutdownHook API, its purpose for registering shutdown hooks, typical use cases such as resource cleanup, state saving, and logging, and provides practical Java and Groovy code examples while noting that hook execution order is unspecified.
ShutdownHook Introduction
The java.lang.Runtime#addShutdownHook method allows you to register a piece of code (a hook) that the JVM will execute when it begins its shutdown sequence, regardless of whether the termination is normal or caused by an exception.
How It Works
The addShutdownHook method accepts a Thread instance; when the JVM is about to exit, this thread is started to perform cleanup or other actions.
Typical scenarios include:
Resource release and cleanup: Ensure files, network connections, etc., are properly closed to avoid leaks.
State saving: Persist necessary data before the program terminates.
Logging: Record shutdown logs for later analysis.
Common termination situations supported are JVM abnormal termination, user‑initiated termination (Ctrl+C or IDE stop), and explicit calls to System.exit() .
Note that the execution order of multiple registered hooks is undefined, and long‑running operations should be avoided to prevent delaying JVM shutdown.
Usage Demonstration
In a typical data‑processing task, you might collect results in a thread‑safe collection such as java.util.Vector . By adding a shutdown hook, you can ensure that partially processed data is saved even if the program is interrupted.
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println(3)));
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
@Override
public void run() {
System.out.println(32);
}
}));
System.exit(8);
}With Groovy, you can wrap the hook registration in a closure for brevity:
static def addHook(Closure closure) {
Runtime.getRuntime().addShutdownHook(new Thread(closure))
}Groovy also provides a direct API:
public static void addShutdownHook(Object self, Closure closure) {
Runtime.getRuntime().addShutdownHook(new Thread(closure));
}Source Code Insights
Examining the source of java.lang.Runtime#addShutdownHook reveals that multiple hooks can be registered, and they run concurrently in an unspecified order when the JVM shuts down.
When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. -- By FunTester
Therefore, you can safely register several hooks, but should not rely on any particular execution sequence.
FunTester
10k followers, 1k articles | completely useless
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.