Shutdown Hooks Run At JVM Exit

Register JVM shutdown hooks with Runtime.addShutdownHook, verify they can be removed, and use them for final flush or cleanup on normal exit.

JavaResilience

Code

snippet
public class Main {
    public static void main(String[] args) {
        Thread flush = new Thread(() -> {
            System.out.println("shutdown hook: flush buffers");
        }, "flush-hook");

        // Shutdown hooks run at JVM exit, on normal return or a termination signal
        Runtime.getRuntime().addShutdownHook(flush);
        System.out.println("hook registered");

        Thread removed = new Thread(() -> System.out.println("never runs"));
        Runtime.getRuntime().addShutdownHook(removed);
        boolean ok = Runtime.getRuntime().removeShutdownHook(removed);
        System.out.println("second hook removed: " + ok);

        System.out.println("main finished");
    }
}

What the code does

Shutdown Hooks Run At JVM Exit keeps everything in the class Main and the function main.

Applying it

The demo output is labeled (shutdown hook: flush buffers, hook registered, never runs), so every printed line maps back to its originating operation.

Statements that matter

Thread flush = new Thread(() -> {
System.out.println("shutdown hook: flush buffers");
}, "flush-hook");

Interactive Tools for This Topic

FAQ

What does Shutdown Hooks Run At JVM Exit print when run?
Invoke the file as-is — the `shutdown hook: flush buffers`, `hook registered`, `never runs` prefixes identify which step printed each line.