Daemon Thread in Java: setDaemon() and When the JVM Exits
A daemon thread in Java is a background thread that doesn’t prevent the JVM from exiting. On its own, the JVM shuts down once all user (non-daemon) threads have finished, and any daemon threads still running are simply cut off mid-sentence. You make a thread a daemon with setDaemon(true), which must be called before start(), and check the flag with isDaemon():
Thread cleaner = new Thread(task, "cache-cleaner");
cleaner.setDaemon(true); // before start()
cleaner.start();
System.out.println(cleaner.isDaemon()); // Output: true That convenience comes at a price. If the daemon happens to be writing a file at that moment, the JVM exits halfway through the write: the finally block doesn’t run, close() isn’t called, and the console shows neither an exception nor a warning. An example where finally is silently skipped is in What Happens to a Daemon When the JVM Exits.
User Thread vs Daemon Thread: What’s the Difference
A user thread keeps the JVM alive: as long as it is running, the program won’t exit, even if main finished long ago. A daemon thread doesn’t keep the JVM alive, and when the JVM exits, the daemon is stopped without warning and without running finally. In everything else — scheduling, priority, synchronization — the two are identical.
The rule “the JVM waits for every thread except daemons”, with an example where main ends before another thread, is covered in The main Thread and When a Program Ends. Here is a point-by-point comparison:
| Property | User thread | Daemon thread |
|---|---|---|
| Keeps the JVM alive | Yes: the JVM waits for it to finish | No: the JVM exits without waiting for it |
| What happens when the JVM exits | By then it has already finished on its own (unless the exit came from System.exit() or a signal) | Cut off at any point in its code |
finally, close() in try-with-resources | Run, because the thread reaches the end | Don’t run if the JVM shutdown cut the thread off |
| Default | main and every thread created by a user thread | Threads created by a daemon; virtual threads; ForkJoinPool threads |
| How to set | setDaemon(false) before start(), or do nothing | setDaemon(true) before start(), Thread.ofPlatform().daemon() |
| Typical examples | Handling requests, writing to a file or database, building a report | Cache cleanup, heartbeat, metrics collection, JVM service threads |
The word “daemon” comes from Unix, where it names background processes with no terminal attached. In Java it means exactly one thing: the thread isn’t counted when the JVM decides whether the program can end. A daemon doesn’t run slower, and it isn’t “in the background” in the sense of having a lower priority.
Example: A Daemon Lives as Long as a User Thread Runs
A daemon thread is stopped not when main ends, but when the last user thread ends. While at least one user thread is alive, the daemon keeps working as usual.
The example has two threads. The daemon heartbeat reports every 250 ms that the application is alive, in an infinite loop. The user thread writer “writes” three parts of data with a 300 ms pause before each. main starts both and finishes right away.
public class UserVsDaemon {
public static void main(String[] args) {
Thread heartbeat = new Thread(() -> {
int beat = 0;
while (true) { // infinite loop
System.out.println("heartbeat " + (++beat));
pause(250);
}
}, "heartbeat");
heartbeat.setDaemon(true);
Thread writer = new Thread(() -> {
for (int part = 1; part <= 3; part++) {
pause(300);
System.out.println("writer: part " + part + " written");
}
}, "writer");
heartbeat.start();
writer.start();
System.out.println("main finished; heartbeat daemon: " + heartbeat.isDaemon()
+ ", writer daemon: " + writer.isDaemon());
}
static void pause(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
} heartbeat 1
main finished; heartbeat daemon: true, writer daemon: false
heartbeat 2
writer: part 1 written
heartbeat 3
writer: part 2 written
heartbeat 4
writer: part 3 written The first two lines may swap places: main and the freshly started heartbeat print at almost the same moment. The rest of the order is set by the pauses. The heart beats at 0, 250, 500 and 750 ms; the parts are written at 300, 600 and 900 ms. After the third part there are no user threads left, so the JVM exits and the fifth beat at 1000 ms never comes. The daemon’s infinite loop ended with no break, no exception and not a single line in the log.
Remove the line heartbeat.setDaemon(true) and the program never ends: an infinite loop in a user thread holds the JVM, and only Ctrl+C will stop it.
setDaemon() and isDaemon(): Only Before start()
setDaemon(boolean on) sets the daemon flag and isDaemon() returns it. setDaemon() has to be called before start(): on a running thread it throws IllegalThreadStateException, because the JVM has already taken the thread into account when counting user threads. You can’t turn a started thread into a daemon, or the other way round.
To be precise, the Javadoc says the exception is thrown if the thread is alive (isAlive() returns true). On a thread that has already terminated, the check doesn’t fire:
public class SetDaemonTooLate {
public static void main(String[] args) throws InterruptedException {
Thread worker = new Thread(() -> {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}, "worker");
worker.start();
try {
worker.setDaemon(true); // thread is alive
} catch (IllegalThreadStateException e) {
System.out.println("While running: " + e);
}
worker.join();
worker.setDaemon(true); // thread has finished - no exception
System.out.println("After it finished: isDaemon = " + worker.isDaemon());
}
} While running: java.lang.IllegalThreadStateException
After it finished: isDaemon = true The exception has no message, so nothing follows the class name. The second line isn’t a loophole: the flag changed on a thread that no longer runs anything and can’t be started again, so it has no effect on the program. A “just in case” try/catch around setDaemon() doesn’t help either — the exception signals a bug in the order of calls, and the order is what needs fixing.
setDaemon() inside run() doesn’t work
Calling Thread.currentThread().setDaemon(true) at the top of run() looks natural (“the thread declares itself a background thread”), but by then the thread is already running, and the call throws IllegalThreadStateException. Set the flag from outside, before start(), or in the constructor of a Thread subclass.
Inheritance: A Thread Created by a Daemon Is a Daemon
A new platform thread takes its daemon flag from the thread that creates it. Threads created from main are user threads, because main isn’t a daemon; threads created by a daemon are daemons. The flag is copied in the Thread constructor, not when start() is called, and you can override it with setDaemon() before the thread starts.
public class DaemonInheritance {
public static void main(String[] args) throws InterruptedException {
System.out.println("main: " + Thread.currentThread().isDaemon());
Thread parent = new Thread(() -> {
System.out.println("parent: " + Thread.currentThread().isDaemon());
Thread child = new Thread(() -> { }, "child");
System.out.println("child, created by a daemon: " + child.isDaemon());
Thread saver = new Thread(() -> { }, "saver");
saver.setDaemon(false); // explicitly make it a user thread
System.out.println("saver after setDaemon(false): " + saver.isDaemon());
}, "parent");
parent.setDaemon(true);
parent.start();
parent.join();
Thread sibling = new Thread(() -> { }, "sibling");
System.out.println("sibling, created by main: " + sibling.isDaemon());
}
} main: false
parent: true
child, created by a daemon: true
saver after setDaemon(false): false
sibling, created by main: false The output is deterministic: everything is printed inside parent, and main waits for it with join(). The child and saver threads were never even started, yet they already have the flag.
In practice, inheritance bites like this: a background daemon reacts to some event by starting a separate thread that must save data, and that thread turns out to be a daemon too. If saving matters, it needs an explicit setDaemon(false). Pools built on the default thread factory (newFixedThreadPool, newCachedThreadPool, newSingleThreadExecutor, newScheduledThreadPool) don’t follow inheritance: the factory resets the daemon flag even if the pool was created from a daemon. The exception is newWorkStealingPool(): its threads are always daemons (see When Priorities Are Actually Worth Setting).
When Does the JVM Exit
A Java program ends in one of these cases: the last user thread has finished, someone called System.exit() or Runtime.exit(), the process received a termination signal (Ctrl+C, SIGTERM), or the JVM was stopped forcibly — Runtime.halt(), kill -9, a crash. Daemon threads don’t affect any of these cases, and the case decides whether shutdown hooks run.
| Why the JVM exits | Shutdown hooks | What happens to running threads |
|---|---|---|
| The last user thread has finished | Run | Only daemons are left — they are cut off after the hooks |
System.exit(status) | Run | All are cut off, including user threads and the calling thread itself |
| Ctrl+C, SIGTERM | Run | All are cut off |
Runtime.halt(), kill -9, JVM crash | Don’t run | All are cut off |
System.exit() stops the JVM even while user threads are alive — more in How System.exit() Works. A less obvious detail from the Runtime Javadoc: while shutdown hooks are running, daemon threads keep running too. They are cut off at the very end, once all hooks have finished. The next section uses exactly this to stop a daemon cleanly.
What Happens to a Daemon When the JVM Exits: finally Doesn’t Run
When the JVM exits, a daemon thread stops at whatever line it was executing: it gets no exception, no interrupt(), and neither finally blocks nor close() in try-with-resources run. That is why a daemon must not be given a file or database write unless something guarantees it will finish before the JVM exits.
public class DaemonFinally {
public static void main(String[] args) throws InterruptedException {
Thread saver = new Thread(() -> {
try {
System.out.println("saver: started writing");
Thread.sleep(1000); // a long write
System.out.println("saver: write complete");
} catch (InterruptedException e) {
System.out.println("saver: interrupted");
} finally {
System.out.println("saver: finally - closing the file");
}
}, "saver");
saver.setDaemon(true);
saver.start();
Runtime.getRuntime().addShutdownHook(new Thread(() ->
System.out.println("shutdown hook: JVM is shutting down")));
Thread.sleep(200);
System.out.println("main finished");
}
} saver: started writing
main finished
shutdown hook: JVM is shutting down After 200 ms main ends, no user threads are left, and the JVM runs the shutdown hook and exits. By then the daemon saver is asleep in Thread.sleep(1000), so neither “write complete”, nor “interrupted”, nor the line from finally ever appears. If a real write stood in place of sleep(), the file would be left half-written.
Runtime.addShutdownHook(Thread) registers a thread that the JVM starts during an orderly shutdown. Since daemons are still alive while hooks run, a hook can ask the daemon to stop and give it time to reach finally. Replace the hook in the example with this one:
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
saver.interrupt(); // ask the daemon to stop
try {
saver.join(500); // and wait no longer than 500 ms
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
})); saver: started writing
main finished
saver: interrupted
saver: finally - closing the file Now finally does run, but only because the hook explicitly interrupted the thread: sleep() responded to interrupt() by throwing InterruptedException (how that works is explained in InterruptedException). This is a safety net, not a guarantee. Hooks don’t run on Runtime.halt() or kill -9, and a task that ignores interruption won’t finish within 500 ms. If the work must complete, give it to a user thread (see the last section).
try-with-resources won’t save a daemon
close() in try-with-resources is called by the same mechanism as finally, so a daemon that gets cut off won’t reach it either. For a BufferedWriter this means whatever sat in the buffer and wasn’t flushed with flush() is lost, and the file ends up shorter than what you wrote.
Daemons in the JVM, Thread Pools and Virtual Threads
A running JVM has more daemon threads than you might expect: the JVM’s own service threads, the worker threads of ForkJoinPool (and therefore of CompletableFuture and parallel streams), and every virtual thread. Threads of the regular pools from Executors, on the other hand, are user threads, and a pool that is never shut down keeps the program running.
| Where the thread comes from | Daemon? | What follows from that |
|---|---|---|
main, new Thread(...) from a user thread | No | The JVM waits for it to finish |
new Thread(...) from a daemon | Yes | Inherits the flag; needs an explicit setDaemon(false) if the work matters |
Executors.newFixedThreadPool, newCachedThreadPool, newSingleThreadExecutor, newScheduledThreadPool | No (default factory) | A pool that isn’t shut down keeps the program from exiting — Shutting down a pool |
ForkJoinPool.commonPool(), Executors.newWorkStealingPool() | Yes | runAsync() without waiting for the result loses the task — supplyAsync and runAsync |
| Virtual threads (Java 21) | Always | Without join(), main may not wait for the result — join() with virtual threads |
new Timer() / new Timer(true) | No / yes | A timer created without an argument keeps the JVM alive until cancel() is called |
| JVM service threads: Reference Handler, Finalizer, Signal Dispatcher, Common-Cleaner | Yes | Visible in a thread dump, don’t affect program exit; their priorities are in the thread priority FAQ |
Virtual threads follow a strict rule: isDaemon() always returns true, setDaemon(true) changes nothing, and setDaemon(false) throws IllegalArgumentException — and it does so before checking whether the thread has been started. The Thread.ofVirtual() builder has no daemon() method at all.
public class VirtualDaemon {
public static void main(String[] args) {
Thread vt = Thread.ofVirtual().unstarted(() -> { });
System.out.println("isDaemon: " + vt.isDaemon());
try {
vt.setDaemon(false);
} catch (IllegalArgumentException e) {
System.out.println("setDaemon(false): " + e.getClass().getSimpleName());
}
}
} isDaemon: true
setDaemon(false): IllegalArgumentException Note the two different exceptions. On a running platform thread, setDaemon() throws IllegalThreadStateException (wrong state); on a virtual thread it throws IllegalArgumentException (an invalid argument value in any state).
A Pool of Daemon Threads: Thread.ofPlatform().daemon()
To build a pool out of daemon threads, pass it your own ThreadFactory. In Java 21 the easiest way to get one is the builder: Thread.ofPlatform().name("cleaner-", 1).daemon().factory() creates a factory that produces numbered daemon threads. Such a pool won’t stop the JVM from exiting, even if you forget to shut it down.
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
public class DaemonPool {
public static void main(String[] args) throws InterruptedException {
ThreadFactory factory = Thread.ofPlatform()
.name("cache-cleaner-", 1)
.daemon() // same as daemon(true)
.factory();
ScheduledExecutorService cleaner = Executors.newSingleThreadScheduledExecutor(factory);
cleaner.scheduleAtFixedRate(() -> {
Thread t = Thread.currentThread();
System.out.println(t.getName() + ", daemon: " + t.isDaemon() + " - clearing cache");
}, 0, 300, TimeUnit.MILLISECONDS);
Thread.sleep(700);
System.out.println("main finished, pool not shut down");
}
} cache-cleaner-1, daemon: true - clearing cache
cache-cleaner-1, daemon: true - clearing cache
cache-cleaner-1, daemon: true - clearing cache
main finished, pool not shut down The cleanup runs at 0, 300 and 600 ms, main ends at 700 ms, and the program exits by itself even though nobody called shutdown(). With the default factory the same code would hang forever. For periodic housekeeping this is a deliberate choice: if one run gets cut off, nothing is lost.
Before Java 21 the factory was written as a lambda: create a Thread, call setDaemon(true), return the thread. That code, with a priority and a name, is in When Priorities Are Actually Worth Setting. The Thread.ofPlatform() builder itself is covered in Thread.ofPlatform() and Thread.ofVirtual().
When to Use Daemon Threads and When Not To
Give a daemon thread work that can be cut off at any moment without losing data: periodic cache cleanup, heartbeats, collecting and sending metrics, watching a configuration file. Don’t make a daemon out of a thread that writes files, runs database transactions, sends messages or charges money — anything that has to complete fully or not start at all.
A quick test: imagine the JVM stopping in the middle of any line of run(). If everything is fine after a restart — the cache fills up again, the metric arrives next time — a daemon is fine. If you’re left with a half-written file or a half-done operation, you need a user thread.
A common reason to make an important thread a daemon is “otherwise the program never exits.” The fix for that isn’t the daemon flag but stopping the thread properly: the loop checks a volatile boolean running flag or Thread.currentThread().isInterrupted(), and the application’s shutdown code (or a shutdown hook) clears the flag or calls interrupt() and waits with join(). The thread reaches its finally on its own and exits. Why the flag has to be volatile is explained in volatile in Java.
One last thing: a daemon isn’t a way to “hide” a thread from the rest of the program. It shares the heap with it, needs synchronization like any other thread, and an uncaught exception in it silently ends only that thread.
Frequently Asked Questions
Can the main thread be made a daemon?
No. The JVM itself creates and starts main, and setDaemon() on a started thread throws IllegalThreadStateException. If the program shouldn’t wait for some background work, make the thread that does that work a daemon. The rule with an example is in setDaemon() and isDaemon().
How do I see which threads are daemons in a running application?
Take a thread dump with jstack <pid>: the header line of a daemon thread contains the word daemon, for example "Reference Handler" #9 daemon prio=10 ..., while user threads don’t have it. From code you can get the same through Thread.getAllStackTraces().keySet(), filtering the threads by isDaemon().
Does a daemon thread get less CPU time?
No. The daemon flag only affects whether the JVM waits for the thread on exit. The scheduler treats a daemon exactly like a user thread, and its default priority is inherited from the creating thread as well. If background work needs to be less noticeable, that’s a separate decision — a lower priority or a bounded pool.
main has finished but the program doesn’t exit. How do I find the thread to blame?
Take a jstack dump and look for threads without the word daemon, apart from DestroyJavaVM — that’s the former main waiting for the others. Usually the culprit is a pool that was never shut down (names like pool-1-thread-1), a java.util.Timer created without true, or your own thread with an infinite loop. The fix is shutting down the pool, calling timer.cancel() or stopping the thread properly — see When to Use Daemon Threads.
Comments