Shutdown Hook in Java

Naveen AnamaneniUpdated · 3 min read

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 endsHooks run?
Last user thread finishesYes
System.exit(code)Yes
Ctrl+C, or kill (SIGTERM)Yes
kill -9 (SIGKILL), power loss, crashNo
Runtime.halt(code)No

Methods

MethodDescription
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.

Hook.java▶ Try it
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");
    }
}
Output
Navika wrote 3 notes
main is finished
Hook: saving 3 notes before exit

Explanation: 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.exit inside 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

  1. Easy: Add a hook that prints "Goodbye from Srihitha", and end the program with System.exit(0).
  2. 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.

Quick check: Shutdown hooks

4 questions
1How do you register a shutdown hook?
2Does a hook run after System.exit(0)?
3Does a hook run after kill -9?
4In what order do several hooks run?

Key Takeaways

Was this tutorial helpful?

Lesson 392 of 482