Monday, July 8, 2013

Daemon Thread in java

If we talk about process that were constantly running in background in Unix are known as daemon, much like services in windows. Sometimes you want to create a thread that performs some helper function but you don't want the existence of this thread to prevent the JVM from shutting down. That is what daemon threads are for.

Threads are divided into 2 parts; normal thread and daemon threads. When the JVM starts up, all threads it creates are daemon threads, except the main thread.When a new thread is created, it inherits the daemon status of the thread that created it, so by default any threads created by the main thread are also normal threads.

Daemon thread are like a service providers for other threads running in the same process as daemon thread. It's used for background supporting tasks like handling requests,resources cleanup and only needed while normal threads are executing.


The main difference between the normal thread and daemon thread is that JVM always wait for normal thread to finish, but JVM never wait for daemon thread to finish.

In short, it differ in what happens when they exit. Daemon threads die when the creator thread exits.

So daemon thread is thread that does not prevent the JVM from existing when the programs finishes.The best example for daemon thread is Garbage Collector.
when a thread is created it inherits daemon status of its parent. You can use the setDaemon() method to change the Thread daemon properties.

We can see this with an example 
Output :
When setDaemon() is set false, it works as a normal thread. You can see from the out that JVM wait for worker thread to complete.


When setDaemon() is set true, it works as a daemon thread. You can see from the out that JVM does not wait for the worker thread to complete.

If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

No comments:

Post a Comment