Video in progress
How does the JVM behave when stopped with kill -15 versus kill -9, and when do shutdown hooks run?
On SIGTERM (kill -15) the JVM shuts down in an orderly way: it runs the registered shutdown hooks and the Spring context is closed. A process cannot catch SIGKILL (kill -9). The kernel kills it immediately and no hook runs.
📖 Answer
The JVM shuts down in an orderly way, running hooks, in these cases: the last non-daemon thread finishes, System.exit() is called, or SIGTERM, SIGINT (Ctrl+C) or SIGHUP arrives.
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
log.info("to'xtayapmiz, navbatdagi xabarlarni saqlayapmiz");
queue.flush();
}));
What you need to know about hooks:
- they start in parallel, and the order is not guaranteed;
- a long-running hook holds up the whole shutdown;
- if you call
System.exit()inside a hook, the process hangs.
With kill -9 nothing runs: open transactions are cut off, buffered logs are lost, temp files are not deleted. Runtime.halt() also stops the JVM without running hooks.
In Spring Boot you don't have to write a hook yourself. It registers its own, and @PreDestroy, DisposableBean and SmartLifecycle are called through it. With server.shutdown=graceful (the default since Boot 3.4) new requests are rejected and the in-flight ones are allowed to finish.
Kubernetes sends SIGTERM first, and after terminationGracePeriodSeconds (default 30 s) it sends SIGKILL. In a container Java should be PID 1 (exec java ...), otherwise the shell may not forward the signal to Java.
Sign up to mark studied questions and save your progress.