Card 06/ 08

GotchaDifficulty: Advanced1 min

Why Your Program Will Not Exit

main reaches its last line and prints the completion message. The process does not end, and nothing in the logs says why.

java
Thread poller = new Thread(() -> {
    while (true) {
        checkForWork();
        try {
            Thread.sleep(1_000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return;
        }
    }
});

poller.start();
System.out.println("started");

The virtual machine exits when the last non-daemon thread finishes. main is one, the poller is another, and the poller never finishes — so the process stays alive with nothing useful left to do.

What the daemon flag changes
Compared onNon-daemon, the defaultDaemon
Keeps the process aliveYesNo
Killed at exitNo — the machine waitsYes, wherever it had got to
SuitsWork that must finishBackground polling, monitoring, cleanup
java
poller.setDaemon(true);
poller.start();
must be set before start(), or it throws

For work that must finish, keep it non-daemon and give it a way to stop — a volatile boolean the loop checks, or an interrupt. A thread you cannot ask to stop is a process you cannot shut down.