beginnerFoundations

What is a daemon thread, and how do you create one?

A daemon thread is a background thread that does not prevent the JVM from shutting down. The JVM exits as soon as every non-daemon (user) thread has finished running, and at that point any remaining daemon threads are abruptly terminated without any further cleanup. You create one by calling thread.setDaemon(true) before calling start() -- calling it after the thread has already started throws an IllegalThreadStateException. A thread also inherits the daemon status of whichever thread created it, so any thread spawned from a daemon thread is itself a daemon by default. Daemon threads are a natural fit for background work that should never block shutdown, such as heartbeat pings, periodic cache refreshes, or log flushers.

Ready to master this question?

Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.

Sign in to generate a response

Next Step

Continue to What happens if you call run() directly instead of calling start() on a Thread?← Back to all Java Concurrency & Multithreading questions