Daemon threads run in the background and mostly created by JVM for performing background tasks such as Garbage Collection, and other housekeeping tasks.
Daemon threads are meant to serve user threads and are only needed when the user threads are running, they will not prevent JVM from exiting once all the user threads have completed their execution.
That's why infinite loops which typically exist in the Daemon threads, don't cause any problems, because any code, including the finally block, won't execute after the user threads have finished their execution. For this reason. daemon threads are not recommended for I/O tasks.
However, there is an exception to this rule. The poorly designed code in daemon threads can prevent JVM from exiting. For instance. calling Threads.join() on running daemon thread can block the shutdown of the application.
Here we can see that even if the Daemon thread is running, the program terminates as the main thread which is a daemon thread is terminated.
Daemon threads are meant to serve user threads and are only needed when the user threads are running, they will not prevent JVM from exiting once all the user threads have completed their execution.
That's why infinite loops which typically exist in the Daemon threads, don't cause any problems, because any code, including the finally block, won't execute after the user threads have finished their execution. For this reason. daemon threads are not recommended for I/O tasks.
However, there is an exception to this rule. The poorly designed code in daemon threads can prevent JVM from exiting. For instance. calling Threads.join() on running daemon thread can block the shutdown of the application.
Properties
- Any thread created by the main thread is by default non-daemon because any thread inherits its daemon nature from its parent thread. Since main is a non-daemon thread, any thread created by it will also be a non-daemon thread.
- We can make a thread daemon by calling method setDaemon(true).
- Thread.setDaemon() can only be called before starting the thread. It will throw IllegalThreadStateException if the thread is already started.
- Daemon threads are useful for background supporting tasks such as garbage collection, releasing memory of unused objects and removing unwanted entries from the cache. Most of the JVM threads are daemon threads.
- It is an utmost low priority thread.
Code example
Below code represents the implementation of Daemon thread -
Output
Count from Daemon: 0 Count from Daemon: 1 Main thread finishes
Here we can see that even if the Daemon thread is running, the program terminates as the main thread which is a daemon thread is terminated.
Conclusion
Congratulations!! 🙋 today we discussed Daemon thread with its implementation. I hope you enjoyed this post.
Comments
Post a Comment