Daemon Thread in Java

In Java, a daemon thread is a service provider thread that aids the user thread. Its survival is at the mercy of user threads; hence, when every user thread is killed, the JVM immediately kills this thread.

Many Java daemon threads, such as the finalizer and gc (Garbage Collector), are running automatically.

Points to keep in mind when using Java’s Daemon Thread:

  • It offers services to user threads for assisting processes running in the background.
  • Its only purpose in life is to support user threads.
  • The user threads are what give it life.
  • It is a thread of low priority.

If there is no user thread, why does JVM kill the daemon thread?

The daemon thread’s sole function is to assist the user thread with background supporting tasks. Why should JVM continue to run this thread if there is no user thread? For this reason, if there isn’t a user thread, JVM kills the daemon thread.

Background Threads: Daemon threads are threads that provide support to user threads, performing tasks such as garbage collection, logging, or other maintenance activities. They run in the background without preventing the program from terminating when all user threads finish their execution.

Non-Critical Tasks: Daemon threads are typically used for tasks that are not critical to the main functionality of the program. They are often used for housekeeping activities or background processes that can be safely terminated if all user threads have been completed.

Termination Behavior: If all user threads in a program complete their execution, the Java Virtual Machine (JVM) can exit even if daemon threads are still running. In contrast, if any user threads are still active, the JVM will not exit, ensuring that the program remains functional.

Creation: Daemon threads can be created by invoking the setDaemon(true) method on a thread object before starting it. This marks the thread as a daemon thread. By default, threads created by the program are user threads unless explicitly marked as daemon threads.

Example Use Cases: Examples of daemon thread tasks include background logging, automatic data synchronization, and regular cleanup or maintenance of resources.

Lifecycle: Daemon threads have the same lifecycle as user threads, including states like NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, and TERMINATED. They differ mainly in their impact on program termination.

Careful Resource Handling: Since daemon threads can be abruptly terminated when the main program exits, it’s important to ensure that they don’t perform critical tasks or leave resources in an inconsistent state.

Garbage Collection: Daemon threads can assist in garbage collection activities by marking and cleaning up objects that are no longer reachable.

Implementation: Daemon threads are implemented using the setDaemon(boolean on) method provided by the Thread class in Java.

Creating a Daemon Thread:

All we have to do is call Thread.setDaemon() to make a thread a daemon thread. We’ll use the Thread class extension NewThread in this example.

NewThraed daemonThread = new NewThread();
daemonThraed.setDaemon(true);
daemonThraed.start();

The daemon status of the thread that created it is inherited by all other threads. Any thread started inside the main method is automatically a user thread because the main thread is one.

Only after the Thread object has been constructed and the thread hasn’t been started can the function setDaemon() be used.

An IllegalThreadStateException will be thrown if setDaemon() is attempted while a thread is active:

@Test(excepted = IllegalThreadStateException.class)
Public void whenSetDaemonWhileRunning_thenIllegalThreadStateException()
{
    NewThread daemonThread = new NewThread();
daemonThraed.start();
daemonThread.setDaemon(true);
}

Java Daemon thread methods by Thread class:

Java.lang is used.Java daemon thread is provided with two methods by the thread class.

SI.No               Method                   Description
    1 setDaemon(boolean status) is a public void. It determines whether the active thread is a daemon thread or a user thread.
    2 isDemand(), a public boolean.  To verify if the current process is a daemon.

Properties of Java Daemon Thread:

No Preventing JVM Exit: When all user threads have completed running, daemon threads cannot stop the JVM from quitting. Regardless of whether any daemon threads are active, the JVM stops itself if all user threads are finished with their duties.

Automatic Termination: Daemon threads are unable to prevent the JVM from shutting down once all user threads have finished operating. The JVM shuts down on its own if all user threads have completed their tasks, regardless of whether any daemon threads are running.

Low Priority: Among all Java threads, daemon threads have the lowest priority.

Program:

Example 1:

public class TechVidvan extends Thread {
public void run() {
if(Thread.currentThread().isDaemon())
{
System.out.println("TechVidvan thread work");
}
else{
System.out.println("user thread work");
}
}
public static void main(String[] args) {
TechVidvan t1=new TechVidvan();
TechVidvan t2=new TechVidvan();
TechVidvan t3=new TechVidvan();
t1.setDaemon(true);
t1.start();
t2.start();
t3.start();
}
}

Output:
TechVidvan thread work
user thread work
user thread work

Explanation:

It is established that the Thread class is extended by the class TechVidvan.

Within the TechVidvan class’s execute method:

  • Using the isDaemon() function of the Thread class, it determines whether the thread that is now running is a daemon thread.
  • It prints “TechVidvan thread work” to the terminal if the active thread is a daemon thread.
  • It prints “user thread work” to the console if the active thread is a user thread rather than a daemon thread.

The primary method is:

  • There are three instances of the TechVidvan class created (t1, t2, and t3).
  • The t1 thread is designated as a daemon thread by using the setDaemon(true) function.
  • To begin their concurrent execution, all three threads—t1, t2, and t3—call the start method.

The run method determines if each thread is a user thread or a daemon thread as it runs and prints the appropriate message.

Default Nature of Daemon Thread:

The main thread is always a non-daemon thread by default. All other threads, on the other hand, inherit their parent thread’s daemon characteristics. If the parent thread is a daemon, the child thread will also be one, and vice versa if the parent thread is not a daemon.

Example 2:

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

Output:
Exception in thread “main” java.lang.IllegalThreadStateException
at java.base/java.lang.Thread.setDaemon(Thread.java:1406)
at TechVidvanJava.main(TestDaemonThread2.java:10)
Name: Thread-0
Daemon: false

Explanation:

  • This Java program defines the “TechVidvanJava” class, which is an extension of the Thread class. It uses “Thread.currentThread().getName()” and “Thread.currentThread().isDaemon()” in its “run” method to print the name and daemon status of the active thread, respectively.
  • Two instances of the “TechVidvanJava” class (t1 and t2) are generated in the “main” method. T1 is initially started and set as a daemon thread using “t1.start()” and “t1.setDaemon(true)”, whereas t2 is initially started but not set as a daemon thread.
  • The output of this program, which shows that designating a thread as a daemon should be done before beginning it, will show the name and daemon status of each thread.

Methods of Daemon Thread:

1. Void setDaemon (boolean status):

This technique designates whether the active thread is a user thread or a daemon thread. The tU.setDaemon(true) method can be used to turn a user thread into a daemon, while the tD.setDaemon(false) method can be used to turn a daemon thread into a user thread.

Syntax:

Public final void setDaemon (boolean on)

Parameters:

Indicates that this thread is a daemon thread if true.

Exceptions in a Daemon Thread:

SI.No   EXCEPTIONS               Description
1 IllegalThreadStateException The setDaemon() method will throw an error if it is used after the thread has begun.
2 SecurityException After the thread has begun, if you use the setDaemon() method, it will throw an error.

2. Boolean isDemand():

This technique is used to determine whether the active thread is a daemon. If the thread is a daemon, it returns true. It returns false if not.

Syntax:

Public final boolean isDaemon()

Returns:

If this thread is a daemon thread, this method returns true; otherwise, it returns false.

Program 1:

public class DaemonThread extends Thread
{
    public DaemonThread(String name){
        super(name);
    }
 
    public void run()
    {
        if(Thread.currentThread().isDaemon())
        {
            System.out.println(getName() + " is Daemon thread");
        }
         
        else
        {
            System.out.println(getName() + " is User thread");
        }
    }
    public static void main(String[] args)
    {
        DaemonThread t1 = new DaemonThread("t1");
        DaemonThread t2 = new DaemonThread("t2");
        DaemonThread t3 = new DaemonThread("t3");
        t1.setDaemon(true);
        t1.start();
        t2.start();
        t3.setDaemon(true);
        t3.start();       
    }
}

Output:
t3 is Daemon thread
t2 is User thread
t1 is Daemon thread

Explanation:

  • The “DaemonThread” class, which is an extension of the Thread class, is defined in this Java application. It has an override “run” method and a constructor to set the thread’s name.
  • The “Thread.currentThread().isDaemon()” function is used in the “run” method to determine whether the current thread is a daemon thread. It prints that the thread is a daemon thread if it is one; else, it prints that it is a user thread.
  • Three instances of the “DaemonThread” class (t1, t2, and t3) are created in the “main” method. The commands “t1.setDaemon(true)” and “t3.setDaemon(true)” specifically designate the threads t1 and t3 as daemons. The “start()” method is then used to launch each of the three threads.
  • This application will print if each thread is a user thread or a daemon thread when it is executed.

Exceptions in a Daemon Thread:

IllegalThreadStateException is thrown if the setDaemon() method is called after the thread has been started.

Program 2:

public class DaemonThread extends Thread
{
    public void run()
    {
        System.out.println("Thread name: " + Thread.currentThread().getName());
        System.out.println("Check if its DaemonThread: "
                        + Thread.currentThread().isDaemon());
    }
    public static void main(String[] args)
    {
        DaemonThread t1 = new DaemonThread();
        DaemonThread t2 = new DaemonThread();
        t1.start();
        t1.setDaemon(true);
        t2.start();
    }
}

Runtime Exception:

Exception in thread "main" java.lang.IllegalThreadStateExceptionat java.base/java.lang.Thread.setDaemon(Thread.java:1406)
    at DaemonThread.main(DaemonThread.java:14)

Output:
Thread name: Thread-0
Check if its DaemonThread: false

Explanation:

  • This Java program defines a class called “DaemonThread” that extends the Thread class. In its “run” method, it prints the current thread’s name and checks if it’s a daemon thread using “Thread.currentThread().getName()” and “Thread.currentThread().isDaemon()”.
  • In the “main” method, two instances of the “DaemonThread” class (t1 and t2) are created. t1 is started before being set as a daemon thread using “t1.start()” and “t1.setDaemon(true)”, while t2 is started without being set as a daemon thread.
  • When you run this program, it will print the name and daemon status of each thread, demonstrating that setting a thread as a daemon should be done before starting it to take effect.

Daemons vs User Threads:

Priority: The JVM shuts down when a process has just daemon threads left. This makes sense because a daemon thread doesn’t need to serve another thread while only daemon threads are active.
Usage: User threads are mostly supported in the background by daemon threads. Without interfering with user actions, they manage tasks that assist the main execution.

Properties of Daemon Thread:

  • The thread has the lowest possible priority.
  • When all of the user threads have finished their work, they won’t be able to prevent the JVM from shutting down.
  • The JVM shuts down once all user threads have finished running.
  • If JVM discovers a running daemon thread, it kills the thread and then shuts down the daemon.
  • Whether or whether the Daemon thread is active is of little importance to the JVM.
  • A demon’s traits are passed on from one generation to the next. To put it another way, if one parent is a daemon, the child will also be a daemon, and if the other parent is not a daemon, the child will also be a non-daemon.

Conclusion

In summary, daemon threads in Java are designed for background tasks and non-essential processes that provide support to user threads. They allow a program to perform auxiliary activities without keeping the program running indefinitely after its main functionality has been completed.