Open In App

Daemon Thread in Java

Last Updated : 20 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, daemon threads are low-priority threads that run in the background to perform tasks such as garbage collection or provide services to user threads. The life of a daemon thread depends on the mercy of user threads, meaning that when all user threads finish their execution, the Java Virtual Machine (JVM) automatically terminates the daemon thread.

To put it simply, daemon threads serve user threads by handling background tasks and have no role other than supporting the main execution.

Example of Daemon Thread in Java

Some examples of daemon threads in Java include garbage collection (gc) and finalizer. These threads work silently in the background, performing tasks that support the main execution without interfering with the user’s operations.

Properties of Java Daemon Thread

  1. No Preventing JVM Exit: Daemon threads cannot prevent the JVM from exiting when all user threads finish their execution. If all user threads complete their tasks, the JVM terminates itself, regardless of whether any daemon threads are running.
  2. Automatic Termination: If the JVM detects a running daemon thread, it terminates the thread and subsequently shuts it down. The JVM does not check if the daemon thread is actively running; it terminates it regardless.
  3. Low Priority: Daemon threads have the lowest priority among all threads in Java.

Default Nature of Daemon Thread

By default, the main thread is always a non-daemon thread. However, for all other threads, their daemon nature is inherited from their parent thread. If the parent thread is a daemon, the child thread is also a daemon, and if the parent thread is a non-daemon, the child thread is also a non-daemon.

Note: Whenever the last non-daemon thread terminates, all the daemon threads will be terminated automatically.

Methods of Daemon Thread

1. void setDaemon(boolean status):

This method marks the current thread as a daemon thread or user thread. Setting a user thread as a daemon can be done using thetU.setDaemon(true)', while setting a daemon thread as a user thread can be done using thetD.setDaemon(false)'.

Syntax: 

public final void setDaemon(boolean on)

Parameters:

  • on: If true, marks this thread as a daemon thread.

Exceptions:

  • IllegalThreadStateException: if only this thread is active.
  • SecurityException: if the current thread cannot modify this thread.

2. boolean isDaemon(): 

This method is used to check that the current thread is a daemon. It returns true if the thread is Daemon. Else, it returns false. 

Syntax: 

public final boolean isDaemon()

Returns: 

This method returns true if this thread is a daemon thread; false otherwise

Java




// Java program to demonstrate the usage of
// setDaemon() and isDaemon() method.
 
public class DaemonThread extends Thread
{
    public DaemonThread(String name){
        super(name);
    }
 
    public void run()
    {
        // Checking whether the thread is Daemon or not
        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");
     
        // Setting user thread t1 to Daemon
        t1.setDaemon(true);
             
        // starting first 2 threads
        t1.start();
        t2.start();
 
        // Setting user thread t3 to Daemon
        t3.setDaemon(true);
        t3.start();       
    }
}


Output: 

t1 is Daemon thread
t3 is Daemon thread
t2 is User thread

Exceptions in a Daemon thread 

If you call the setDaemon() method after starting the thread, it would throw IllegalThreadStateException.

Java




// Java program to demonstrate the usage of
// exception in Daemon() Thread
 
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();
         
        // Exception as the thread is already started
        t1.setDaemon(true);
         
        t2.start();
    }
}


Runtime exception: 

Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Thread.java:1352)
at DaemonThread.main(DaemonThread.java:19)

Output: 

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

This clearly shows that we cannot call the setDaemon() method after starting the thread. 

Daemon vs. User Threads

  • Priority: When only daemon threads remain in a process, the JVM exits. This makes sense because when only daemon threads are running, there is no need for a daemon thread to provide a service to another thread.
  • Usage: Daemon threads are primarily used to provide background support to user threads. They handle tasks that support the main execution without interfering with the user’s operations.

Understanding daemon threads is essential for Java developers to effectively manage thread behavior and optimize application performance.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads