Week 114 — What is a daemon thread?

Question of the Week #114
What is a daemon thread?
2 Replies
kali
kali6d ago
Threads allow executing multiple operations in parallel. Once all threads terminate, the application is shut down. An exception to this rule are daemon threads which don't prevent the application from stopping. When all non-daemon threads have finished, the JVM initiates its shutdown logic and stops all daemon threads no matter what these are currently doing. The following example creates two threads, one of which being a daemon thread. The daemon thread sleeps 3 seconds while the non-daemon thread only sleeps for one second:
Thread nonDaemon = new Thread(() -> {
try {
System.out.println("non-daemon thread started");
Thread.sleep(1000);
System.out.println("non-daemon thread finished");
} catch(InterruptedException e) {
//should normally not happen in this example
Thread.currentThread().interrupt();
System.err.println("non-daemon thread interrupted");
}
});
Thread daemon = new Thread(() -> {
try {
System.out.println("daemon thread started");
Thread.sleep(3000);
System.out.println("daemon thread finished");
} catch(InterruptedException e) {
//should normally not happen in this example
Thread.currentThread().interrupt();
System.err.println("daemon thread interrupted");
}
});
daemon.setDaemon(true);
nonDaemon.start();
daemon.start();
Thread nonDaemon = new Thread(() -> {
try {
System.out.println("non-daemon thread started");
Thread.sleep(1000);
System.out.println("non-daemon thread finished");
} catch(InterruptedException e) {
//should normally not happen in this example
Thread.currentThread().interrupt();
System.err.println("non-daemon thread interrupted");
}
});
Thread daemon = new Thread(() -> {
try {
System.out.println("daemon thread started");
Thread.sleep(3000);
System.out.println("daemon thread finished");
} catch(InterruptedException e) {
//should normally not happen in this example
Thread.currentThread().interrupt();
System.err.println("daemon thread interrupted");
}
});
daemon.setDaemon(true);
nonDaemon.start();
daemon.start();
When running this example, it can be seen that both threads start and that the non-daemon thread finishes after one second. Once that happens, the JVM stops and the daemon thread is killed without printing the text daemon thread finished or daemon thread interrupted.
non-daemon thread started
daemon thread started
non-daemon thread finished
non-daemon thread started
daemon thread started
non-daemon thread finished
📖 Sample answer from dan1st
kali
kali6d ago
Daemon thread is a thread which destroys after all the thread.. even the last priority threads will destroy before the daemon thread
Submission from aarvy

Did you find this page helpful?