Card 06/ 08
All 8 cards
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.
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.
| Compared on | Non-daemon, the default | Daemon |
|---|---|---|
| Keeps the process alive | Yes | No |
| Killed at exit | No — the machine waits | Yes, wherever it had got to |
| Suits | Work that must finish | Background polling, monitoring, cleanup |
poller.setDaemon(true);
poller.start();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.