Video in progress
What is a daemon thread, and how does it differ from a regular thread?
A daemon thread is a "background" thread. The JVM waits only for the non-daemon threads to finish; when they are done, daemon threads are stopped midway and the process exits.
📖 Answer
Thread t = new Thread(() -> {
while (true) {
cleanupCache();
sleepQuietly(60_000);
}
});
t.setDaemon(true); // before start()!
t.start();
As soon as main finishes, the JVM exits, and this thread dies too without any warning. finally blocks may not run.
So don't do important work in a daemon thread: writing to a file, a DB commit, sending a message can all get cut off halfway. Jobs that suit a daemon: monitoring, cache cleanup, heartbeats.
Two details:
- if you call
setDaemon()afterstart(), you get anIllegalThreadStateException; - a new thread inherits the daemon flag from the thread that created it.
Virtual threads are always daemon, and you can't make them setDaemon(false).
Sign up to mark studied questions and save your progress.