Sunday 20 September 2015

Daemon threads

Daemon threads in Java are like a service providers for other threads or objects running in the same process as the daemon thread.

Example of daemon thread is the garbage collection.

Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. If normal threads are not running and remaining threads are daemon threads then the interpreter exits.

A daemon thread is a thread that does not prevent the JVM from exiting when the program finishes but the thread is still running.

setDaemon(true/false): This method is used to specify that a thread is daemon thread.

public boolean isDaemon(): This method is used to determine the thread is daemon thread or not.

class WorkerThread extends Thread {
     public WorkerThread() {
         setDaemon(true);
         /**When false (user thread) the Worker thread continues to run.
          * When true (daemon thread) the Worker thread terminates
          * when the main thread terminates.
          **/
     }

     public void run() {
         int count=0 ;
         while (true) {
            System.out.println("Hello from Worker "+count++) ;
            try {
                  sleep(5000);
            } catch (InterruptedException e) {}
         }
     }
}

public class DaemonTest {
     public static void main(String[] args) {
            new WorkerThread().start();
            try {
                   Thread.sleep(7500);
            } catch (InterruptedException e) {
                   System.out.println("Interrupted Exception");
            }
            System.out.println("Main Thread ending") ;
      }
}

Output:
Hello from Worker 0
Hello from Worker 1
Main Thread ending

Points to remember:

Default nature of a thread is non daemon because Thread inherits its daemon nature from the Thread which creates it i.e. parent Thread and since main thread (Thread class) is a non-daemon thread.
A thread will remain non-daemon until explicitly made daemon by calling setDaemon(true).

Thread should setDaemon before start it otherwise It will throw IllegalThreadStateException if corresponding Thread is already started and
running.

Difference between Daemon and Non Daemon:

JVM doesn’t wait for any daemon thread to finish before existing.

Daemon Threads are treated differently than User Thread when JVM terminates, finally blocks are not called, Stacks are not unwounded and JVM just exits.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...