All topics
library
advanced

Shutdown Hooks & Graceful Termination

Register cleanup logic for JVM shutdown and design applications for graceful termination.

A shutdown hook is a thread that runs when the JVM is shutting down — via System.exit(), Ctrl+C (SIGINT/SIGTERM), or the last non-daemon thread finishing.

Shutdown hook = a 'close out' procedure at a store. When the 'closing time' signal comes (shutdown), the staff (hooks) rush to finish tasks: close the register (flush buffers), lock the doors (close connections), turn off lights (release resources).

Key Concepts

1
Registration: Runtime.getRuntime().addShutdownHook(new Thread(() -> { // cleanup: close connections, flush buffers, release locks }));
2
Shutdown hook guarantees: - Hooks run concurrently (not in any specific order) - All hooks must complete before JVM exits - Hooks run for normal shutdown (System.exit, SIGTERM) but NOT for kill -9 (SIGKILL) or JVM crash
3
Design for graceful shutdown: 1. Use a volatile boolean flag: volatile boolean running = true; 2. Check the flag in your main loop: while (running) { ... } 3. In the shutdown hook: set running = false, wait for in-flight work to finish 4. Use ExecutorService.shutdown() + awaitTermination()
4
Spring Boot handles this automatically: @PreDestroy methods and ApplicationContext closing. But standalone Java applications need manual hooks.
5
Daemon threads: JVM doesn't wait for daemon threads to finish. If all non-daemon threads end, daemon threads are killed immediately (no shutdown hook for them). Use Thread.setDaemon(true) for background tasks that shouldn't prevent JVM exit.