Daemon Thread in Java


Daemon Java ThreadViews 3752

In the previous articles, we have seen various topics related to user threads. In this article, we will understand about daemon threads in Java, their uses, methods with examples and see differences between daemon thread vs user thread.

Java Daemon thread

Daemon Thread in Java

Daemon thread in Java is a system-generated thread that runs in the background and supports the user thread process. It is of low priority and does tasks like garbage collection, finalizer, etc. It runs automatically and we do not need to invoke it separately. The life of the daemon thread depends on the user thread which means when the user thread ends, the JVM automatically terminates the daemon threads and does not wait for daemon thread completion.

When a thread starts the execution, it inherits the daemon status of the parent’s thread. This is the reason that the main thread in Java is a non-daemon thread and all the threads that we create are child threads. By default, these child threads are also non-daemon.

Methods of Daemon thread

Even though the daemon thread is a system-generated thread, it is possible to set a new thread as a daemon and also check if a thread is a daemon or not.

Below are the different methods of the daemon thread in Java.

MethodDescription
void setDaemon(boolean status)It sets the current thread as a user thread or a daemon thread. If status is true, it sets as a daemon thread, if false, it sets as a user thread
boolean isDaemon()Checks if the current thread is a daemon thread or a user thread.
Returns true if it is a daemon thread else it returns false.

Example

The below example demonstrates the working of setDaemon() method and isDaemon() methods of a Daemon thread in Java. In the run() method, we check if the thread is a user or daemon thread using the isDaemon() method. The method returns true if it is a daemon thread else returns false. We can set the current thread as a daemon using the setDaemon() method before calling the start() method. The parameter should be true to set as a daemon thread else it considers as a user thread. Hence d1 is a daemon thread and d2,d3 are user threads.

public class DaemonThreadDemo extends Thread {
  String name;
  public void run() {
  
    name = Thread.currentThread().getName();
    if(Thread.currentThread().isDaemon())
      System.out.println(name + " is a daemon thread");
    else
      System.out.println(name + " is a user thread");
  }

  public static void main(String[] args) {
    DaemonThreadDemo d1 = new DaemonThreadDemo();
    DaemonThreadDemo d2 = new DaemonThreadDemo();
    DaemonThreadDemo d3 = new DaemonThreadDemo();
    
    d1.setDaemon(true);
    
    d1.start();
    d2.start();
    
    d3.setDaemon(false);
    d3.start();
  }

}
Thread-2 is a user thread
Thread-1 is a user thread
Thread-0 is a daemon thread

Exceptions

Daemon threads in Java also throw exceptions in certain conditions. Suppose, we try to set a thread as a daemon thread or invoke the setDaemon() method after the thread starts, it will throw IllegalThreadStateException. Hence, we can always use the setDaemon() method only before calling the start() method.

For example, the below Java code will result in an exception since we are trying to set the thread as a daemon thread after starting the thread execution.

public class DaemonException extends Thread {

  public void run() {
    System.out.println("Thread running");
  }
  public static void main(String[] args) {
    DaemonException d1 = new DaemonException();
    DaemonException d2 = new DaemonException();
    
    d1.start();
    
    d1.setDaemon(true); //Exception
    
    d2.start();

  }

}
Thread running
Exception in thread "main" java.lang.IllegalThreadStateException
  at java.base/java.lang.Thread.setDaemon(Thread.java:1402)
  at DaemonException.main(DaemonException.java:12)

Daemon thread vs User thread

This is the most commonly asked interview question in multithreading in Java. Below are the main differences between daemon thread and user thread.

User threadDaemon thread
High priority threadLow priority thread
Runs in foregroundRuns in background
Performs specific complex taskPerforms supporting task
JVM always waits for active user thread to complete before shutdownJVM does not wait for daemon thread to complete before shutdown
Created by the Java application for executing some taskCreated by the JVM
It is independentIt depends on the user threads

Conclusion

In this tutorial, we have seen what is a Daemon thread in Java, how to set a thread as a daemon thread and check if the current thread is a daemon or user thread. We have also seen the exception that can arise due to incorrect usage of daemon thread methods. Finally, we have discussed the major differences between daemon and user threads.

Reference

Translate ยป