Shutdown Hook in Java
A shutdown hook in Java is a thread that the JVM runs while the program is shutting down. It is used for last-minute cleanup: saving unsaved data, closing connections, writing a final log line. You register a hook with Runtime.getRuntime().addShutdownHook(thread). The hook runs when the program ends normally, when System.exit is called, or when the user presses Ctrl+C, but not when the process is killed forcibly. In this lesson, you will learn how to add a hook and what it can safely do.
When Shutdown Hooks Run
| How the program ends | Hooks run? |
|---|---|
| Last user thread finishes | Yes |
System.exit(code) | Yes |
Ctrl+C, or kill (SIGTERM) | Yes |
kill -9 (SIGKILL), power loss, crash | No |
Runtime.halt(code) | No |
Methods
| Method | Description |
|---|---|
Runtime.getRuntime().addShutdownHook(Thread hook) | It is used to register a hook. |
Runtime.getRuntime().removeShutdownHook(Thread hook) | It unregisters a hook before shutdown starts. |
Example: Saving State on Exit
Let's see an example where a hook runs after main finishes.
public class Hook {
static int unsavedNotes = 0;
public static void main(String[] args) {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
System.out.println("Hook: saving " + unsavedNotes
+ " notes before exit");
}, "save-hook"));
unsavedNotes = 3;
System.out.println("Navika wrote " + unsavedNotes + " notes");
System.out.println("main is finished");
}
}Navika wrote 3 notes
main is finished
Hook: saving 3 notes before exitExplanation: The hook is a normal, unstarted Thread. The JVM starts it during shutdown, after main has ended, so it sees the final value of unsavedNotes and can save it.
Rules for Writing Hooks
- Keep them short. The operating system may force-kill a program that takes too long to shut down.
- Don't depend on order. If there are several hooks, they run at the same time, in no fixed order.
- Don't call
System.exitinside a hook. It can hang the JVM. - Make them thread-safe. Other threads may still be running when hooks start.
Common Mistakes
Starting the hook thread yourself. Pass it unstarted; the JVM starts it.
Adding a hook after shutdown has begun. It throws IllegalStateException.
Expecting hooks after kill -9 or a crash. They don't run.
Practice
- Easy: Add a hook that prints "Goodbye from Srihitha", and end the program with
System.exit(0). - Harder: Write a program that counts up every second in a loop and, in a shutdown hook, writes the last count to a file. Stop it with Ctrl+C and check the file.
Key Takeaways
Was this tutorial helpful?