User and Daemon Threads

User and Daemon Threads

learninjava
Mar 24, 2015 - Java
 

User and Daemon ? 

A User thread is a thread that is created by the User i.e, the application where as a Daemon thead is a thread that is created to serve the user thread. A Daemon thread is usually made to run in the background continuously. User threads are terminated once the run() method completes. Daemon threads are automatically terminated by the JVM when only threads running are the daemon threads.
 Remember!
1. Garbage Collector is a good example of a daemon thread
2. Any thread that listens to the incoming requests can be made daemon thread
3. Services sending the inputs to a dashboard or monitoring service can be created as a daemon thread
Daemon thread example is shown below :
loading...
Output:

Exiting main thread...
In run method of daemon thead...

 Remember!
1. The JVM exits if only threads running are the daemon threads i.e, the JVM does not wait for the daemon threads unless join() method is called on it
2. The JVM does not call the finally methods of daemon threads
3. Use setDaemon(true) only before calling start() method
Observe that since the thread we created is a daemon thread, the JVM does not wait for the thread to complete and hence it prints the statement in thread only once and exits. Also, the JVM ignore the statement in finally block. As discussed, JVM does not call the final methods of daemon threads.
Note: The above output is NOT guaranteed to be same as shown. Sometimes, the JVM may exit without even printing the statement in while loop.
 Remember!
The output of the below example shows that the JVM exits without waiting for the while loop to complete. Also observe that the statement in finally is not displayed (rule 2). Uncomment the join() statement and re-run the example. Now you will see that the JVM is waiting for the daemon thread to complete (rule 1).
User & Daemon thread example is shown below :
loading...
Output:

In run method of daemon thead...
In run method of user thead...
Exiting main thread...
In finally method of daemon thread...
In run method of daemon thead...
In finally method of daemon thread...
In run method of daemon thead...
In finally method of user thread...
In finally method of daemon thread...

 Remember!
From the output it is clear that the JVM waits for the user thread to complete. During this time, it processes the daemon thread and also the finally method of daemon thread. Once the 3 second sleep of user thread is over, the loop breaks and the user thread completes. JVM then observes that the only thread running now is the daemon thread. JVM then exits immediately.
Thats all folks !! Happy coding. If you feel this helped you, keep supporting us by   or  or  below or on the articles on social media.
 
Like us on: