Have a Question?

If you have any question you can ask below or enter what you are looking for!

What is Daemon thread and How to make Daemon thread?

What is Daemon thread and How to make Daemon thread?
  • By default main thread is always non-demon and for all remaining threads, demon nature will be inherited from parent to child that is if the parent thread is demon then automatically child thread is also a demon. And if parent thread is non-demon then automatically child thread also non-demon.
  • When the JVM starts, it creates a thread called “Main”. Your program will run on this thread unless you create additional threads yourself. The first thing the “Main” thread does is to look for your static void main (String args[]) method and invoke it. That is the entry-point to your program. If you create additional threads in the main method those threads would be the child threads of the main thread.
  • Daemon threads are like a service provider for other threads or objects running in the same process as the daemon thread. 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.
  • Note:- it is impossible to change demon nature of main thread because its already started by JVM at the beginning.
package com.java4us;

public class Test extends Thread {
    public static void main(String args[]) {
        Test t = new Test();
        System.out.println(t.isDaemon()); // false
        Thread.currentThread().setDaemon(true); // Exception in thread "main" java.lang.IllegalThreadStateException
        t.setDaemon(true);
        System.out.println(t.isDaemon()); // true
    }
}
  • Whenever last non-demon thread terminates automatically all demon threads will be terminated irrespective of their position. 
package com.java4us;

public class Test extends Thread {
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("Child thread");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }
    public static void main(String args[]) throws InterruptedException {
        DeadLock d = new DeadLock();
        d.setDaemon(true); // line-1
        d.start();
        System.out.println(d.isDaemon());
        System.out.println("end of main");

    }
}
  • If we are commenting line 1 both main and child threads are non-demon and hence both thread will be executed until their completion.
  • If we are not commenting line 1 then main thread is non-demon and child thread is demon hence whenever main thread terminates automatically child thread will be terminated.
Tags:  , , , , , ,

Leave a Reply

Your email address will not be published.