Monday, 19 January 2015

What is Daemon Thread in Java

Daemon Thread:

There are two types of threads user thread and daemon thread. The daemon thread is a service provider thread. It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

Points to remember for Daemon Thread:

It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
Its life depends on user threads.
It is a low priority thread.

Why JVM termintates the daemon thread if there is no user thread remaining ?

The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.

Methods for Daemon thread:

The java.lang.Thread class provides two methods related to daemon thread

public void setDaemon(boolean status): is used to mark the current thread as daemon thread or user thread.
public boolean isDaemon(): is used to check that current is daemon.

Example of Daemon thread:

class Test 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){
Test t1=new Test();
Test t2=new Test();
t1.setDaemon(true);
t1.start();
t2.start();
}
}

Output:Name: thread-0
Daemon: true
Name: thread-1
Daemon: false


Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.

class Test 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){
Test t1=new Test();
Test t2=new Test();
t1.start();
t1.setDaemon(true);  //will throw exception here
t2.start();
}
}

Output: exception in thread main: java.lang.IllegalThreadStateException

No comments:

Post a Comment