What is a daemon thread and when would you use one? — Cracked Java
// Concurrency & Multithreading · Thread Fundamentals & Lifecycle
JuniorTheory

What is a daemon thread and when would you use one?

A daemon thread is a background thread that does not keep the JVM alive: when the only remaining threads are daemons, the JVM exits — abruptly, without running their remaining code or finally blocks. You use them for non-critical background chores like housekeeping, monitoring, or heartbeats.

Setting it

You must call setDaemon(true) before start(); doing it after throws IllegalThreadStateException. Daemon status is inherited: a thread spawned by a daemon is a daemon by default. The main thread and most application threads are non-daemon ("user") threads.

Thread heartbeat = new Thread(() -> {
    while (true) {
        sendPing();
        try { Thread.sleep(1000); } catch (InterruptedException e) { return; }
    }
});
heartbeat.setDaemon(true);   // MUST be before start()
heartbeat.start();
// when main() returns and no user threads remain, the JVM kills heartbeat

The JVM shutdown rule

The JVM keeps running while at least one non-daemon thread is alive. Once the last user thread finishes, the JVM begins shutdown and daemon threads are terminated where they stand — no exception is thrown into them, finally blocks may not run, and buffered writes may be lost.

When to use one

  • Background maintenance: cache eviction sweeps, metrics flushers, JIT/GC-style helpers.
  • Watchdogs, heartbeats, log shippers — work that should never block process exit.
  • The famous example is the JVM's own GC and finalizer threads, which are daemons.

Mark your status