What is the difference between a daemon thread and a user thread in Java, and how do you make a thread a daemon?
answer
- User thread keeps JVM alive; daemon does not
- JVM exits when last user thread ends
- setDaemon(true) BEFORE start()
- Alive thread -> IllegalThreadStateException
- New thread inherits creator's daemon flag
basics
~20 sA user thread keeps the program alive: absent System.exit() or a signal, the JVM waits for every user thread to finish. A daemon thread is a background helper that does not keep it alive. Call thread.setDaemon(true) before start() to make one.
solid answer
~50 sJava threads are either user threads (the default) or daemon threads. The JVM stays alive as long as at least one user thread is running; absent System.exit() or an OS signal, it starts shutting down once the last one finishes. Daemon threads are background helpers the JVM does not wait for. You mark a thread as daemon with setDaemon(true), which must be called before start() (on a live thread it throws IllegalThreadStateException). A new thread inherits the daemon status of the thread that creates it, so threads spawned by the main thread are user threads by default. Daemons suit fire-and-forget background work like housekeeping or monitoring, where abrupt termination is acceptable. Avoid daemons for work that must complete or that holds resources needing clean shutdown, because daemons are killed without running finally blocks or releasing resources when the JVM exits.
code
java · 17 linespublic class DaemonDemo {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
while (true) {
System.out.println("daemon working...");
try { Thread.sleep(200); } catch (InterruptedException e) { return; }
}
});
worker.setDaemon(true); // MUST be before start()
worker.start();
Thread.sleep(500);
System.out.println("main ending");
// main (the only user thread) returns here -> JVM exits,
// abandoning the daemon mid-loop without further output.
}
}go deeper
Knows the default is a user thread, that setDaemon(true) must precede start(), and that daemons do not keep the JVM alive.
Explains JVM-exit semantics precisely (last user thread), the IllegalThreadStateException from setDaemon on a live thread, and gives appropriate daemon use cases.
Discusses inheritance of the daemon flag, the abrupt-termination/no-cleanup hazard, and why daemons are unsuitable for resource-holding or must-complete work.
Frames daemon usage in lifecycle/shutdown design — prefers explicit shutdown coordination (executor shutdown, shutdown hooks) over relying on daemon abandonment, and reasons about data-loss risk at process exit.
## Terms first A **thread** is an independent path of execution within a running Java program; a single JVM process can run many threads at once. The **JVM** (Java Virtual Machine) is the process that runs your program; when it has nothing left to do it **exits** (the process ends). Every Java thread is classified as one of two kinds: - **User thread** (also called a non-daemon thread): the *default*. It represents real, foreground work. - **Daemon thread**: a *background* helper thread. ## The one rule that defines the difference The JVM keeps running **as long as at least one user (non-daemon) thread is alive**, unless something calls `System.exit()` or an OS signal starts the shutdown first. The moment the **last user thread finishes**, the JVM begins to shut down — and it does **not** wait for any daemon threads. They may keep running while any shutdown hooks run, but when the JVM terminates they are simply **abandoned** (stopped abruptly). So the practical meaning is: *user threads keep the application alive; daemon threads do not.* The `main` thread that runs your `main` method is itself a user thread, which is why a simple program stays alive until `main` returns (and until any other user threads it started also finish). ## How you make a thread a daemon You call `setDaemon(true)` on a `Thread` object **before** you call `start()`: ```java Thread t = new Thread(task); t.setDaemon(true); // must be BEFORE start() t.start(); ``` If you call `setDaemon(...)` while the thread is alive (started and not yet finished), Java throws `IllegalThreadStateException`; on a thread that has already terminated, the Javadoc leaves the behaviour unspecified. The daemon flag is fixed for the life of the thread once it is running. A virtual thread (final since JDK 21) is always a daemon: `isDaemon()` returns true, and at JDK 25 and 27 `setDaemon(false)` on one throws `IllegalArgumentException`. ## Inheritance of the flag A newly created thread **inherits the daemon status of the thread that created it**. The `main` thread is a user thread, so any thread you create from `main` is a user thread by default — you must explicitly opt into daemon status. A thread created *by* a daemon thread will itself be a daemon unless you change it. ## When to use which Use **daemon** threads for *fire-and-forget* background services where abrupt termination at JVM exit is acceptable: periodic monitoring, metrics flushing on a best-effort basis, cache eviction, watchdogs; the JDK's own `Finalizer` and `Reference Handler` threads are daemons. Use **user** threads for any work that *must complete* before the program can correctly exit — for example writing a file, committing a transaction, or anything that must run cleanup. ## The danger of daemons When the JVM exits because the last user thread finished, daemon threads are stopped **without** running their `finally` blocks or releasing resources cleanly — there is no graceful unwinding. So never rely on a daemon to flush important data or close critical resources; that work can be lost mid-operation. ## Quick mental model Think of a daemon thread as a janitor in an office building: useful while people (user threads) are there, but the moment the last employee leaves, the building locks up and the janitor is sent home immediately, whether or not they finished mopping.
- What happens to a daemon thread's finally block when the JVM exits because the last user thread ended?It may not run at all. Daemon threads are abruptly terminated at JVM exit without guaranteed stack unwinding, so finally blocks and resource cleanup can be skipped — which is why daemons must not be used for critical cleanup.
- If main spawns a non-daemon thread that loops forever, does the JVM exit when main returns?No. main returning does not end the JVM while another user (non-daemon) thread is still alive. The JVM keeps running until that looping user thread terminates.
Daemon threads are like a hotel's background music: it plays while guests (user threads) are around, but the moment the last guest checks out, the hotel powers down and the music just stops mid-song — nobody waits for it to finish.
- Saying daemon threads run with lower priority — daemon status is unrelated to priority
- Thinking you can call setDaemon on a thread that is already running
- Believing the JVM waits for daemon threads to finish
- Assuming a daemon's finally blocks always run at JVM exit (they may not)
Assumes JDK 27, the same in JDK 25: platform threads follow the setDaemon and Runtime shutdown rules given here, and virtual threads, final since JDK 21, are always daemons.
context
- Thread (Java SE 27 & JDK 27)docs.oracle.com
- Runtime (Java SE 27 & JDK 27)docs.oracle.com