«Back to Home

Core Java

Topics

Daemon Thread In Java

Daemon Thread
Daemon thread is a service provider, which provides the Services to the user thread. It is a low priority thread, which runs in the background to perform the tasks. Its life depends on the mercy of user threads i.e. when all the user threads dies, JVM automatically terminates this thread.
 
There are many Java Daemon threads running automatically such as garbage collection (gc), finalizer etc.
 
Important points for Daemon Thread

It provides the Services to the user threads for the background supporting tasks. It has no role in life than to serve the user threads.
 
Its life fully depends on the user threads.
 
It is a low priority thread.
 
JVM terminates the daemon thread if there is no user thread. Do you know why?

The main purpose of Daemon thread provides the Services to the user thread for the background supporting task due to which if there is no user thread, JVM terminates Daemon thread.
 
Methods for Daemon thread by Thread class

public void setDaemon(boolean status)

This method is used to mark the current thread as Daemon thread or User thread.
 
public boolean isDaemon()

This method is used to check whether the current thread is Daemon or not.
 
Let’s see an example, given below.
 
Code
  1. public class DaemonThread extends Thread {  
  2.     public void run() {  
  3.         if (Thread.currentThread().isDaemon()) { //checking for a daemon thread    
  4.             System.out.println("I am Daemon thread");  
  5.         } else {  
  6.             System.out.println("I am User thread");  
  7.         }  
  8.     }  
  9.   
  10.     public static void main(String[] args) {  
  11.         DaemonThread t1 = new DaemonThread();  
  12.         DaemonThread t2 = new DaemonThread();  
  13.         t1.setDaemon(true); //it's a daemon thread    
  14.         t1.start();  
  15.         t2.start();  
  16.     }  
  17. }  
25
 
Output

26

If we want to create a User thread as Daemon thread, it should not be started, else it will throw an exception IllegalThreadStateException.
 
Let’s see an example, given below.
 
Code
  1. public class DaemonThread extends Thread {  
  2.     public void run() {  
  3.         System.out.println("Name: " + Thread.currentThread().getName());  
  4.         System.out.println("Daemon: " + Thread.currentThread().isDaemon());  
  5.     }  
  6.     public static void main(String[] args) {  
  7.         DaemonThread t1 = new DaemonThread();  
  8.         t1.start();  
  9.         t1.setDaemon(true); //throw exception  
  10.     }  
  11. }  
27

Output

28

Summary

Thus, we learnt the main purpose of Daemon thread is that it provides the Services to User thread for the background supporting task and also learnt, how to create it in Java.