Quiz: Daemon Thread in Java: setDaemon() and When the JVM Exits
Study the lesson first: Daemon Thread in Java: setDaemon() and When the JVM Exits
Total: 7 questions
1. What is a daemon thread in Java and how does it differ from a user thread?
What is a daemon thread in Java and how does it differ from a user thread?
A daemon thread is a background thread that does not prevent the JVM from exiting. On its own, the JVM shuts down once all user (non-daemon) threads have finished; any daemon threads still running are cut off at whatever line they are executing.
- Keeps the JVM alive: a user thread does, a daemon does not.
- When the JVM exits: a user thread has usually finished on its own by then; a daemon is stopped with no exception and no
interrupt(), itsfinallyblocks andclose()in try-with-resources do not run. - Default:
mainand threads created by user threads are user threads; threads created by a daemon, virtual threads andForkJoinPoolthreads are daemons. - How to set:
setDaemon(true)beforestart()orThread.ofPlatform().daemon(); check withisDaemon().
In everything else they are the same: a daemon is scheduled the same way, has a normal priority and needs synchronization like any other thread.
2. When does a Java program exit, and what happens to the threads that are still running?
When does a Java program exit, and what happens to the threads that are still running?
The JVM exits in one of four cases:
- The last user thread has finished - shutdown hooks run, then the remaining daemon threads are cut off. The end of
mainon its own decides nothing. System.exit(status)orRuntime.exit()- hooks run, then all threads are cut off, including user threads and the calling thread itself.- A termination signal (Ctrl+C, SIGTERM) - hooks run, threads are cut off.
Runtime.halt(),kill -9, a JVM crash - hooks do not run, threads are cut off.
Daemon threads do not affect any of these cases. One detail from the Runtime Javadoc: daemon threads keep running while shutdown hooks execute and are cut off only after all hooks have finished.
3. When can you call setDaemon(), and what happens if you call it after start()?
When can you call setDaemon(), and what happens if you call it after start()?
setDaemon(boolean on) is called before start(); isDaemon() returns the current value of the flag. A started thread cannot be turned into a daemon or back.
- If the thread is alive (
isAlive()returnstrue),setDaemon()throwsIllegalThreadStateExceptionwith no message. - On a terminated thread there is no exception: the flag changes, but it has no effect on the program, because the thread no longer runs anything and cannot be started again.
- Calling
Thread.currentThread().setDaemon(true)at the beginning ofrun()also throwsIllegalThreadStateException: by then the thread is already started. Set the flag from outside beforestart()or in the constructor of aThreadsubclass. - The
mainthread cannot be made a daemon: the JVM itself starts it.
Wrapping setDaemon() in try/catch is pointless: the exception signals a mistake in the order of calls, and it is the order that needs fixing.
4. How does a new thread get its daemon flag?
How does a new thread get its daemon flag?
A new platform thread inherits the daemon flag from the thread that creates it. The flag is copied in the Thread constructor, not at start(): what matters is who called new Thread(...), not who started the thread. Before the start the value can be overridden with setDaemon().
- Threads created from
mainare user threads, becausemainis not a daemon. - Threads created by a daemon are daemons. If such a thread must, for example, save data, it needs an explicit
setDaemon(false). - Pools from
Executorsdo not follow inheritance: the default factoryExecutors.defaultThreadFactory()resets the daemon flag even when the pool is created from a daemon.
5. Does a finally block run in a daemon thread when the JVM exits, and how can you let a daemon finish cleanly?
Does a finally block run in a daemon thread when the JVM exits, and how can you let a daemon finish cleanly?
No. When the JVM exits, a daemon stops at the line it was executing: no exception is thrown into it, interrupt() is not called, finally blocks and close() in try-with-resources do not run. With a BufferedWriter, everything not yet flushed with flush() is lost and the file stays incomplete.
Since daemon threads keep running while shutdown hooks execute, a hook can ask the daemon to stop and wait for it:
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
saver.interrupt();
try {
saver.join(500);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
This is a safety net, not a guarantee: hooks do not run on Runtime.halt() or kill -9, and a task that ignores interruption will not finish in the allotted time. Work that must complete belongs in a user thread.
6. Which JDK threads are daemon threads, and how do you create a pool of daemon threads?
Which JDK threads are daemon threads, and how do you create a pool of daemon threads?
- Daemons: worker threads of
ForkJoinPool.commonPool()andExecutors.newWorkStealingPool(), the thread ofnew Timer(true), JVM service threads (Reference Handler, Finalizer, Signal Dispatcher, Common-Cleaner) and all virtual threads. - Not daemons: threads of
newFixedThreadPool,newCachedThreadPool,newSingleThreadExecutor,newScheduledThreadPoolwith the default factory, and the thread ofnew Timer()- it keeps the JVM alive untilcancel()is called.
For virtual threads isDaemon() always returns true, setDaemon(true) changes nothing, and setDaemon(false) throws IllegalArgumentException in any thread state. The Thread.ofVirtual() builder has no daemon() method.
To make a pool of daemons, pass it your own ThreadFactory. In Java 21 the easiest way to get one is the builder:
ThreadFactory factory = Thread.ofPlatform()
.name("cache-cleaner-", 1)
.daemon()
.factory();
ScheduledExecutorService cleaner = Executors.newSingleThreadScheduledExecutor(factory);
Such a pool does not prevent the JVM from exiting even if nobody shuts it down. Before Java 21 the factory was written as a lambda that called setDaemon(true) on every thread it created.
7. When should a thread be a daemon, and when must it not be?
When should a thread be a daemon, and when must it not be?
Give a daemon work that can be cut off at any moment without losing data: periodic cache cleanup, a heartbeat, collecting and sending metrics, watching configuration. A thread that writes files, runs database transactions or sends messages must not be a daemon - anything that has to finish completely or not start at all.
A quick check: imagine the JVM stopping in the middle of any line of run(). If everything is fine after a restart, a daemon is fine; if a half-written file or a half-done operation is left behind, you need a user thread.
If the program "does not exit" because of an important thread, the cure is not the daemon flag but stopping the thread: the loop checks a volatile boolean flag or isInterrupted(), and the shutdown code (or a shutdown hook) clears the flag or calls interrupt() and waits with join(). A jstack dump shows which thread keeps the JVM alive: user threads have no daemon word in their header line.