Daemon thread in java:

Daemon thread is a low priority thread providing services to the user thread. This thread runs in the background to perform tasks such as garbage collection.

Major Properties:

It cannot prevent the JVM from exiting when all the user threads finish their execution.

JVM terminates itself when all user threads finish their execution. If JVM finds a daemon thread running, it terminates the thread and after that shutdown itself.

Methods:

  1. void setDaemon (boolean status): It is used to set the current thread as daemon thread or user thread. For example, if we have a user thread m then m.setDaemon(true) will make it a daemon thread. If we have a daemon thread m then by invoking m.setDaemon(false) it will get converted into a user thread.
  2. boolean isDaemon ():
    It is used to check that the current is daemon. It will return true if the thread is daemon else it returns false.

Exceptions in Daemon thread:

If we call the setDaemon() method after the thread has started, it will throw an exception named IllegalThreadStateException.

A sample example 1 :

File Name: MyNewThread.java

public class DaemonTh1 extends Thread{

public void run (){

// checking whether the current thread is a daemon thread

if(Thread.currentThread().isDaemon()){

System.out.println (“The daemon thread is now working”);

}

else {

System.out.println (“The user thread is now working”);

}

}

public static void main (String[] args){

// thread creation

DaemonTh1 th1= new DaemonTh1 ();

DaemonTh1 th2= new DaemonTh1();

DaemonTh1 th3= new DaemonTh1 ();

// now th1 becomes a daemon thread

th1.setDaemon(true);

//starting threads

th1.start();

th2.start();

th3.start();

}

}

Output:

The daemon thread is now working

The user thread is now working

The user thread is now working

 

A sample example 2 :

File Name: MySecondThread.java    

class DaemonTh2 extends Thread {

public void run() {

System.out.println (“Name: ” + Thread.currentThread().getName());

System.out.println (“Daemon: ” + Thread.currentThread().isDaemon());

}

public static void main(String[] args) {

DaemonTh2 t1= new DaemonTh2();

DaemonTh2 t2= new DaemonTh2();

 // starting threads

t1.start();

// exception will be thrown here

t1.setDaemon (true);

t2.start();

}

}

Output:

exception in thread main: java.lang.IllegalThreadStateException

Daemon vs User Threads (Comparison) :

  1. Priority: When the daemon threads are the only threads, the interpreter exits. This happens because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.
  2. Usage: Daemon thread is to provide services to user thread for background supporting processes.