Daemon Thread Does Not Block Exit

Mark background threads as daemons before start: the JVM exits as soon as only daemons remain, without waiting for their loops to finish.

JavaResilience

Code

snippet
public class DaemonLifecycle {

    public static void main(String[] args) throws InterruptedException {
        Thread heartbeat = new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(100);
                    System.out.println("heartbeat tick");
                } catch (InterruptedException stopped) {
                    return; // 中断即退出
                }
            }
        });
        heartbeat.setDaemon(true); // 必须在 start 之前设置,否则抛异常
        heartbeat.start();

        Thread worker = new Thread(() -> System.out.println("worker done"));
        worker.start();
        worker.join();

        // 只剩守护线程存活:main 返回后 JVM 立即退出,不等心跳循环
        System.out.println("heartbeat is daemon: " + heartbeat.isDaemon());
        System.out.println("heartbeat still alive: " + heartbeat.isAlive());
    }
}

How it works

Daemon Thread Does Not Block Exit keeps everything in the class DaemonLifecycle.

Iteration happens inside while (true) — everything outside it runs once.

Applying it

Running the file prints labeled results such as heartbeat tick, worker done, heartbeat is daemon: — each operation’s effect is visible in the output.

Statements that matter

Thread heartbeat = new Thread(() -> {
while (true) {
try {
Thread.sleep(100);
System.out.println("heartbeat tick");
} catch (InterruptedException stopped) {
return; // 中断即退出
}
}
});

Interactive Tools for This Topic

FAQ

What does Daemon Thread Does Not Block Exit print when run?
Run it as a complete program — the output lines carry labels such as `heartbeat tick`, `worker done`, `heartbeat is daemon:`.