Lesson · Multithreading Fundamentals
Daemon Threads: threads that do not keep the JVM alive
14 min readDaemon Threads
A daemon thread is a thread the JVM is allowed to abandon. The role is fixed at creation, with setDaemon(true) before start, and it changes exactly one thing: the running JVM stops counting that thread when it decides whether to exit. Housekeeping that can lose its last work item belongs there; anything that must commit does not.
A role fixed at birth
Every platform thread is either a user thread (non-daemon) or a daemon thread. The flag changes exactly one decision: whether the running JVM counts this thread when it asks whether any work must still finish. Scheduling, locks and exceptions behave identically.
The role is set with setDaemon(true), and the javadoc is blunt about the timing: the method must be invoked before the thread is started. On a live thread it throws IllegalThreadStateException, because the exit rule needs the flag to be stable once the JVM is running the thread.
A new platform thread inherits the daemon status of the thread that creates it, along with its priority and thread group. Threads created by main are non-daemon, since main itself is one, so a plain new Thread(task).start() produces another thread the JVM will wait for.
Thread housekeeper = new Thread(DaemonThreadsDemo::sweep, "housekeeper"); housekeeper.setDaemon(true); // BEFORE start: a thread's role is fixed at birth housekeeper.start(); Thread worker = new Thread(task); // inherits its creator's status System.out.println(worker.isDaemon()); // false: main is a user thread // housekeeper.setDaemon(true); // on a live thread: IllegalThreadStateException
- Call setDaemon before start. After start() the thread is live and the call throws IllegalThreadStateException.
- Daemon status is inherited. A thread created from main is a user thread unless you say otherwise; isDaemon() answers the question.
- Nothing else changes. Daemons take the same locks, the same priorities and the same exception paths; the flag only affects the JVM's exit decision.
- Virtual threads are always daemons and cannot be flipped to non-daemon, by design (forward link: virtual threads).
setDaemon must happen before start: a thread's role is fixed at birth.
The JVM exits when only daemons remain
The rule is short: the JVM keeps running while at least one non-daemon thread is alive. When the last one finishes, or when someone calls System.exit(), the shutdown sequence begins and the JVM halts shortly afterwards.
There is no farewell for daemon threads. They are stopped abruptly at whatever instruction they reached: a finally block is not guaranteed to complete, an open stream is not flushed, and a lock they hold is not released by code. If losing the last unfinished work item changes the meaning of the data, that work cannot live on a daemon.
The one nuance is that an orderly shutdown first runs the registered shutdown hooks, which do get a real turn before the halt. That is the tool for the flush you cannot afford to lose, and it is the next section.
- The last non-daemon thread terminates, or some thread calls System.exit(status).
- The runtime starts the shutdown sequence: registered shutdown hooks run, concurrently and in no defined order.
- The JVM halts, stopping every remaining daemon thread where it stands.
- No cleanup in that last moment is guaranteed: no finally, no flush, no unlock.
A daemon thread is a promise that the JVM may cut it off at any moment.
Daemon lab · the JVM exit gate
start and finish threads, then read the gatescripted scenarios
ran main(); the gate waits for it to return
user thread: commits a real batch
second user thread, same rule
cache eviction: losing the last sweep costs nothing
flushes counters: the last tick may be lost
closed: shutdown() lets the workers retire when idle
JVM status
JVM alive: 1 non-daemon thread
holding the gate: main
Start threads, finish them, and watch the gate count live non-daemon threads.
Housekeeping yes, commit no
The test for daemon eligibility is not how important the thread feels, but what the last unfinished work item is worth. A cache eviction sweep that misses its final pass loses nothing the next start cannot rebuild. A write-behind buffer that misses its final pass loses rows.
The second test is what the thread holds. A thread owning a lock, a file or a socket cannot be abandoned cleanly: the JVM stops it mid-critical-section, and no code on the way out releases the resource. Other threads then wait on state that nobody will repair.
| Job | Daemon? | Why |
|---|---|---|
| Cache eviction sweep | yes | A missed final pass costs memory, not truth; the next run rebuilds the state. |
| Metrics flush loop | yes | Losing the last interval is a rounding error on a dashboard. |
| Watchdog or heartbeat reporter | yes | Its job is observation; if the JVM is gone there is nothing left to observe. |
| Write-behind buffer | no | The buffer holds data that is not durable anywhere else, so an abrupt stop deletes it. |
| Transaction or batch flush | no | Half-committed work has no meaning; the finish or the rollback has to run. |
| Anything holding a lock or a file | no | A daemon stopped mid-section never runs its finally, so waiters wait for state nobody repairs. |
Ask what the last unfinished work item is worth. If the answer is not zero, the thread is not a daemon.
Shutdown hooks: the orderly exit path
Runtime.getRuntime().addShutdownHook(new Thread(...)) registers a thread to run when the JVM begins an orderly shutdown: the last non-daemon thread has finished, or somebody called System.exit(). Your platform's SIGTERM triggers it too, while SIGKILL does not, and neither does Runtime.halt(), which stops everything immediately.
Hooks run concurrently, in no defined order, while the application is already half dead. Keep them quick, idempotent and free of dependencies that may themselves be shutting down: flush the buffer, close the file, deregister the node. A hook that waits forever on a service that is also going away simply delays the kill.
One trap sits inside the mechanism: calling System.exit() from inside a shutdown hook deadlocks the shutdown, because the JVM is waiting for hooks and the hook is asking the JVM to shut down.
- Hooks run; daemons do not get a turn. The flush that must not be lost belongs in a hook or on a counted thread.
- They run concurrently and unordered. Do not assume one hook finished before another started.
- Keep hooks short and self-contained. Anything slow or network-bound belongs in normal lifecycle code, where timeouts exist.
- Never call System.exit() from a hook. The shutdown is already in progress and would end up waiting on itself.
A shutdown hook is a registry of last cleanup calls, not a place for logic.
JVM exit gate
the JVM leaves when the last non-daemon thread finishescounted: user threads
live count: 3Every started non-daemon thread is one reason for the JVM to stay up.
exit gate
opens when live non-daemon threads = 0
shutdown hooks run herenot counted: daemon threads
They hold no vote in the exit decision, however long they intend to run.
abandoned at the halt
A daemon is stopped where it stands: no signal, no interrupt, and no guarantee that a finally block completes. It is the exit rule that makes setDaemon a promise about lost work.
ThreadFactory: a daemon family in one place
Setting the flag one thread at a time does not scale to code that creates threads in bulk. A ThreadFactory is a single object with a single method, newThread(Runnable), and it is where a family of threads gets names, priorities and the daemon flag once.
Pool threads are exactly the threads an executor will create later, which makes the factory the right place to apply policy: a name prefix so thread dumps read clearly, daemon status for loss-tolerant housekeeping, and an uncaught exception handler for reporting (forward link: the handler chain).
ThreadFactory daemonFactory = runnable -> { Thread t = new Thread(runnable, "metrics-flusher"); // names show up in thread dumps t.setDaemon(true); // policy once, for the whole family return t; }; Thread t = daemonFactory.newThread(task); t.start();
Policy belongs in the factory. When code creates threads in bulk, the factory is where names, priorities, daemon status and handlers stop being copy-pasted.
The pool that pins the JVM open
Here is the trap that costs afternoons. Executors.defaultThreadFactory() creates every new thread as a non-daemon thread, and a pool's workers are long-lived: core threads stay parked, waiting for work, until the pool is shut down. A pool nobody closed therefore keeps the JVM alive after main has returned, with no output and no obvious culprit.
It is the classic reason a small program hangs on exit, and in tests it is why the runner sits there after the last assertion. The pool's own lifecycle API is the fix: shutdown() stops accepting tasks and lets queued work finish, shutdownNow() interrupts busy workers and returns the tasks that never ran, and awaitTermination() is what makes the caller wait for the outcome.
Since Java 19, ExecutorService implements AutoCloseable, so try-with-resources is the tidy form: close() performs shutdown and then awaits termination. That is the modern default for every pool you write.
| Call | What it does | When to use it |
|---|---|---|
| shutdown() | Stops accepting tasks; queued tasks still run; idle workers stop | the normal end of a pool's life |
| shutdownNow() | Interrupts busy workers and returns the tasks that never ran | failure paths, timeouts, test teardown |
| awaitTermination(t, u) | Blocks until the pool terminates or the deadline passes | when the program must not move on early |
| close() (Java 19+) | shutdown() plus awaitTermination(), for try-with-resources | every new pool you write today |
Pool threads are non-daemon, so an unclosed pool pins the JVM open. shutdown() plus awaitTermination is the real lifecycle tool.
Two questions before you write setDaemon
Write the decision down before the code, because the answers decide both the flag and the shutdown path. These are also the answers an interviewer will ask you to defend.
- What does the last unfinished work item cost? Zero (a sweep, a metric tick) can be a daemon; anything with a value runs on a counted thread or inside a shutdown hook.
- What does the thread hold? Locks, buffers, connections and temp files need a code path that releases them, and the exit gives a daemon no such path.
- Who stops it? A daemon has no stop protocol; it dies with the JVM. A non-daemon needs an explicit lifecycle (a flag, an interrupt, a pool shutdown) so it can finish on its own terms.
- Will the JVM exit at all? In a long-running server the core threads are non-daemon and hooks handle the exit. The daemon question matters most in tools, tests and short-lived programs, which is exactly where the exit path is the interesting one.
Daemon is a budget decision: this work may be lost. Make it deliberately.
main returned and the process is still running
The exit gate counts live non-daemon threads, and Executors.defaultThreadFactory creates every pool worker as non-daemon, so a pool nobody closed holds the gate open indefinitely. "It hangs on exit" in a small program, and a test runner that never finishes after the last assertion, are usually this. The fix is lifecycle, not force-killing the process: shutdown() plus awaitTermination(), or try-with-resources on a JDK where ExecutorService.close() exists (Java 19 and later).
Interview angles
When does the JVM exit?+
When the last non-daemon thread terminates, or when System.exit() or Runtime.halt() is called. At that point every remaining daemon thread is abandoned where it stands, and Runtime.halt() skips shutdown hooks as well.
Can you call setDaemon after start()?+
No. It throws IllegalThreadStateException, because the role must be fixed before the thread is live. New platform threads inherit their creator's daemon status, priority and group.
Common misconception: People expect daemon status to be a settable property like the thread name. It is closer to a construction parameter, and the inherited default is what makes surprise non-daemon threads possible.
Why must a daemon thread not hold critical resources?+
Because the JVM can stop it at an arbitrary instruction: finally blocks are not guaranteed, buffers are not flushed, and a held lock is never released by code, so other threads wait on state nobody will repair.
A small program prints its last line and then never exits. What do you suspect, and how do you fix it?+
A live non-daemon thread, in practice an ExecutorService that was never shut down: default pool workers are non-daemon and idle core threads never retire on their own. shutdown() plus awaitTermination() ends it, and ExecutorService.close() (Java 19+) wraps both for try-with-resources.
jstack or a thread dump names the survivor: a pool-N-thread-M worker parked in the pool's work queue is the signature. The gate is doing exactly what it was told, because from its point of view the pool still has work to offer.
Follow-up: Would making the pool's threads daemons be a correct fix here?
How do shutdown hooks relate to daemons?+
Hooks run during an orderly shutdown, before the halt; daemon threads are not signalled at all, they are simply stopped. So the must-not-lose flush goes into a hook (or onto a counted thread), and loss-tolerant housekeeping can stay on daemons.
Hooks run concurrently and unordered, so they must not depend on each other, and calling System.exit() inside a hook deadlocks the shutdown. SIGKILL and Runtime.halt() skip hooks entirely.
Is a daemon thread a lower priority thread?+
No: priority and daemon status are independent. A daemon can run at maximum priority, and it still does not keep the JVM alive, because the flag affects only the exit decision, never scheduling.