skip to content

How does the JVM's shutdown sequence handle its triggers, shutdown hooks, daemon threads and calls to System.exit?

level: principalimportance: nice to knowfreq 28%

answer

  1. Triggers: last user thread, System.exit, OS signal
  2. Daemons never delay exit
  3. Sequence: run+await hooks -> stop daemons -> exit
  4. Runtime.halt skips hooks; SIGKILL skips everything
  5. Hooks run concurrently, no built-in timeout

basics

~20 s

The JVM starts shutting down when the last non-daemon thread ends, System.exit() is called, or an OS signal arrives. It runs every shutdown hook and waits for them, then stops any daemons still running. Daemons never delay exit.

solid answer

~50 s

The JVM starts its shutdown sequence on three triggers: the last live non-daemon thread terminates, code calls System.exit(code) / Runtime.exit(), or an external event such as SIGTERM or Ctrl-C arrives. Daemon threads never count toward keeping it alive. Once shutdown begins, the JVM starts every registered shutdown hook (an unstarted Thread you supplied) concurrently, alongside any threads still alive, and waits for the hooks to finish; hooks are the sanctioned place to flush and release resources. Then the JVM terminates: every remaining thread, daemon or not, stops executing Java code at once, and no finally block runs. Calling System.exit from a hook blocks that hook forever, so shutdown never finishes. Runtime.halt() skips the sequence entirely and is the forcible last resort; SIGKILL never reaches the JVM at all. So: must-finish work on user threads, best-effort flush in hooks, nothing that matters on daemons.

go deeper

for a junior

Knows the JVM exits when the program's main work is done or System.exit is called, and that some cleanup code can run at exit.

for a middle

States the three triggers (last user thread, System.exit, an OS signal), that daemons don't delay exit, and that shutdown hooks run during shutdown for cleanup.

for a senior

Orders the sequence (run+await hooks, then abandon daemons), distinguishes SIGTERM vs SIGKILL, and places cleanup appropriately across hooks/executors/AutoCloseable.

for a principal

Reasons about the full lifecycle: hook concurrency/ordering hazards, no built-in hook timeout, halt() as escape hatch, the indefinite block from System.exit inside a hook, and codifies an application-wide shutdown contract.

## The three ways shutdown starts The `Runtime` Javadoc lists three events that start the shutdown sequence: 1. **Natural exit** — the **last user (non-daemon) thread** finishes. The JVM continuously tracks how many non-daemon threads are alive; when that count reaches zero, there is no foreground work left, so it shuts down. 2. **Programmatic exit** — code calls `System.exit(code)` (which delegates to `Runtime.getRuntime().exit(code)`). This forces shutdown *regardless* of how many user threads are still running. 3. **External event** — an interrupt or a signal from the operating system, such as Ctrl-C or the `SIGTERM` that `kill` or a container stop sends. Daemon threads are irrelevant to trigger (1): the JVM never waits for them. So you cannot keep a JVM alive with daemons alone — start a daemon-only program and it exits immediately after `main` returns. ## The orderly shutdown sequence When any trigger fires, the JVM runs the shutdown sequence the `Runtime` Javadoc defines: 1. **Run shutdown hooks.** All hooks registered via `Runtime.getRuntime().addShutdownHook(thread)` are **started concurrently** (they are unstarted `Thread` objects you supplied). The JVM then **blocks until every hook thread has finished**. Hooks run alongside any daemon or non-daemon threads still alive — this is the window the platform gives you to flush buffers, close files/sockets, stop services, and so on. Because hooks run concurrently, they must be thread-safe and avoid depending on each other's ordering. 2. **Terminate.** After all hooks complete, the JVM terminates with the status code, and every remaining thread — daemons and any non-hook user threads still alive — is immediately prevented from executing further Java code: `finally` clauses, uncaught exception handlers and try-with-resources closes do not run. This is where daemons are abandoned without unwinding. There is no exit-time finalization pass either: neither `Runtime` nor `System` has a `runFinalizersOnExit` method at JDK 25 or 27, though the JDK's `Finalizer` daemon thread, like any live thread, can still run finalizers while the hooks run. Key consequence: **shutdown hooks run, daemons do not get cleanup.** That is the architectural lever — put best-effort cleanup in hooks, never in a daemon's `finally`. ## Interactions and edge cases - **`System.exit()` from within a hook:** Calling `System.exit()` (or `addShutdownHook`) once shutdown is already in progress is problematic. Adding a hook during shutdown throws `IllegalStateException`. Calling `System.exit()` from a hook **blocks indefinitely**: only the first call starts the sequence, so that hook never finishes and the shutdown sequence never completes. - **`Runtime.halt(code)`:** The forcible escape hatch. It terminates the JVM **immediately**, without starting the shutdown sequence or waiting for one already in progress, so no further hook work happens. Use only when orderly shutdown is impossible (e.g., a hook hung). - **Hook timeouts:** The JVM does **not** impose a built-in timeout on hooks — a hook that blocks forever can hang shutdown. Robust hooks bound their own work. (Container orchestrators add their own SIGTERM→SIGKILL grace period.) - **OS signals:** `SIGTERM` (the polite "please stop," e.g. `kill` or a container stop) triggers the **orderly** sequence, so hooks run. `SIGKILL` (`kill -9`) terminates the process at the OS level — the JVM never gets control, so **no** hooks, no daemons cleanup, nothing. - **Uncaught exception in the last user thread:** If the final user thread dies from an uncaught exception, that still counts as the thread terminating, so natural shutdown proceeds (after the uncaught-exception handler runs). ## Designing around the sequence A principal-level mental model for where work belongs: | Need | Mechanism | Why | |---|---|---| | Must finish before exit | user thread / `ExecutorService.shutdown()`+`awaitTermination` | keeps JVM alive / bounded drain | | Best-effort flush during shutdown | shutdown hook | runs in the orderly sequence, before daemons are killed | | Deterministic resource release | try-with-resources / `AutoCloseable` | tied to scope, not exit timing | | Safety-net native cleanup | `Cleaner` | reachability-based, not exit-based | | Throwaway background chore | daemon thread | abandonment is acceptable | | Forced immediate stop | `Runtime.halt()` | bypasses a stuck sequence | ## One-paragraph summary The JVM starts shutting down when no user threads remain, `System.exit` is called or a signal arrives; daemons never delay this. Shutdown then runs all registered hooks concurrently and waits for them — the only sanctioned cleanup window — after which daemons are abandoned and the process ends. `Runtime.halt` and `SIGKILL` skip the sequence entirely. Place must-complete work on user threads/executors, best-effort cleanup in hooks, and treat daemons as expendable.

  • What is the difference between Runtime.exit() and Runtime.halt()?
    exit() (what System.exit delegates to) initiates the orderly shutdown sequence — it runs all shutdown hooks and waits for them before terminating. halt() terminates the JVM immediately, without starting the shutdown sequence or waiting for one in progress, so hooks get no further time. halt is the escape hatch when an orderly shutdown is stuck.
  • If a registered shutdown hook blocks forever, what happens to JVM shutdown?
    Shutdown hangs. The JVM starts hooks concurrently and waits for them all to finish, with no built-in timeout, so a non-terminating hook prevents the process from exiting until something forcibly kills it (Runtime.halt or an external SIGKILL). Hooks must bound their own work.

  • Saying daemons can keep the JVM alive
  • Believing shutdown hooks have a guaranteed time limit enforced by the JVM
  • Assuming Runtime.halt() runs shutdown hooks
  • Thinking SIGKILL gives the JVM a chance to run hooks
  • Claiming System.exit() inside a hook starts a fresh, clean shutdown

shutdown hooks (Runtime.addShutdownHook)
Java 1.3
Runtime.halt
Java 1.3

Assumes JDK 27, the same in JDK 25: the shutdown sequence and termination rules quoted from the Runtime Javadoc; there is no exit-time finalization pass and no runFinalizersOnExit.

context