Demon Threads

  1. The threads which are executing in the background are called Demon Threads, Example Garbage Collector, Signal Dispatched, Attach Listener etc.
  2. The objective of demon thread is to provide support for non demon threads.(Main Thread)
    Example : If main thread runs with low memory then JVM runs with garbage collector to destroy useless objects so that number of bytes of free memory will be improved.With this free memory main thread can continue its execution.
  3. Usually demon threads has low priority but based on our requirement demon threads can run with high priority also.
  4. We can check demon nature of a thread by using isDemon() method of thread class.
    public boolean isDemon()
  5. We can change demon nature of a thread by using setDemon() method
    public void setDemon(boolean b)
    but changing demon nature is possible before starting of a thread only.After starting a thread if we are trying to change the demon nature then we will get runtime exception saying IllegalThreadStateException.
  6. By default main thread is always non demon and for all remaining threads demon nature will be inherited from Parent Thread to Child Thread i.e If the parent thread is demon then automatically child thread is also demon and if the parent thread is non demon then automatically child thread is also non demon.
  7. If it impossible to change the demon nature of main thread because it is already started by JVM at the beginning.
  8. When ever last non demon thread terminates, automatically all demon threads will be terminated, irrespective of their position.
public class DemonThreadDemo {
	public static void main(String[] args) {
		System.out.println(Thread.currentThread().isDaemon());
		//Thread.currentThread().setDaemon(true); //java.lang.IllegalThreadStateException
		MyThread myThread = new MyThread();
		System.out.println(" Child Thread : " + myThread.isDaemon());
		myThread.setDaemon(true);
		System.out.println(" Child Thread : " + myThread.isDaemon());
	}
}
class MyThread extends Thread{
	public void run() {
		System.out.println("My Thread executing");
	}
}

Example : Demon Thread is terminated once all main thread terminates

public class DemonThreadDemo2 {
     public static void main(String[] args) {
         MyThreadDemo childThread = new MyThreadDemo();
         childThread.setDaemon(true);
         childThread.start();
         System.out.println("Execution of main Thread"); //This line wont be printed since demon thread terminates; comment setDemon(true) line to execute this line
     }
 }
 class MyThreadDemo extends Thread{
     public void run(){
         System.out.println("Executing child thread");
         try {
             Thread.sleep(2000);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
         System.out.println("Execution of Child Thread completed");
     }
 }

1 thought on “Demon Threads”

Leave a Comment