Importance of isDaemon() method in Java?


A daemon thread is a low-priority thread in java which runs in the background and mostly created by JVM for performing background tasks like Garbage Collection(GC).

If no user thread is running then JVM can exit even if daemon threads are running. The only purpose of a daemon thread is to serve user threads. The isDaemon() method can be used to determine the thread is daemon thread or not.

Syntax

Public boolean isDaemon()

Example

class SampleThread implements Runnable {
   public void run() {
      if(Thread.currentThread().isDaemon())
         System.out.println(Thread.currentThread().getName()+" is daemon thread");
      else
         System.out.println(Thread.currentThread().getName()+" is user thread");
   }
}
// Main class
public class DaemonThreadTest {
   public static void main(String[] args){
      SampleThread st = new SampleThread();
      Thread th1 = new Thread(st,"Thread 1");
      Thread th2 = new Thread(st,"Thread 2");
      th2.setDaemon(true); // set the thread th2 to daemon.
      th1.start();
      th2.start();
   }
}

Output

Thread 1 is user thread
Thread 2 is daemon thread

raja
raja

e

Updated on: 23-Nov-2023

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements