Categories: Java

Daemon thread in Java

A daemon thread in Java is a background thread with low priority that runs operations like garbage collection. A service provider thread in Java that offers services to the user thread is known as a daemon thread. Its survival is at the mercy of user threads; consequently, the JVM automatically kills this thread when all the user threads have expired.

Example:
Numerous Java daemon threads, including gc and finalizer, are automatically running.

Note:

  • The main thread is always non-daemon by default, but all other threads will inherit their daemon nature from their parents.
  • In other terms, if a parent is a daemon, the child will also be a daemon, and if a non-daemon, the child will also be a non-daemon.
Java Daemon thread methods by Thread class:

1. void setDaemon(boolean status): is used to specify whether the active thread is a user thread or a daemon thread.

Syntax:

public final void setDaemon(boolean on)

2. boolean isDaemon(): to affirm that current is daemon. This method returns true if this thread is a daemon thread; false otherwise

Syntax:

public final boolean isDaemon()
Example:
// Java program to demonstrate the usage of
// setDaemon() and isDaemon() method.

public class Coderz extends Thread
{
  public Coderz(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)
  {
  
    Coderz th1 = new Coderz("th1");
    Coderz th2 = new Coderz("th2");
    Coderz th3 = new Coderz("th3");
  
    // Setting user thread t1 to Daemon
    th1.setDaemon(true);
      
    // starting first 2 threads
    th1.start();
    th2.start();

    // Setting user thread t3 to Daemon
    th3.setDaemon(true);
    th3.start();    
  }
}
Output:
th1 is Daemon thread
th2 is User thread
th3 is Daemon thread
Example: Exception in a Daemon thread
// Java program to demonstrate the usage of
// exception in Daemon() Thread

public class Coderz extends Thread
{
  public void run()
  {
    System.out.println("Thread name: " + Thread.currentThread().getName());
    System.out.println("DaemonThread : "
            + Thread.currentThread().isDaemon());
  }

  public static void main(String[] args)
  {
    Coderz th1 = new Coderz();
    Coderz th2 = new Coderz();
    th1.start();
    
    // Exception as the thread is already started
    th1.setDaemon(true);
    
    th2.start();
  }
}
Output:
Exception in thread "main" java.lang.IllegalThreadStateException
at java.base/java.lang.Thread.setDaemon(Thread.java:1406)at Coderz.main(Coderz.java:20)
Thread name: Thread-0
DaemonThread : false

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

Note: also read about the Java Thread Priority

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

18 hours ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

3 days ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

3 weeks ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

1 month ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

1 month ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

2 months ago