How To Create Daemon Thread in Java?

Learn: How to create daemon thread in java? Can we make daemon thread as non daemon? Why daemon thread is required in java?
By Preeti Jain Last updated : January 26, 2024

Daemon Thread

Daemon is a thread which executes in the background. Garbage Collector is an example of daemon thread as we have seen garbage collector runs in the background.

Purpose

Purpose of daemon thread is to provide support for user thread.

Example

For Example, if user thread is executing with low memory (i.e. user thread need more memory to execute) then jvm will call garbage collector(daemon thread) to destroy useless objects by memory space will get free and user thread can be executed quickly.

Usually, Threads having high priority will get a chance first to execute but daemon threads run with the lowest priority(but it does not mean that daemon thread can't run with highest priority it can if required).

Related Methods

There are few methods related to Daemon Thread

  1. public boolean isDaemon()
  2. public void setDaemon(boolean b)

In the above methods described as :

  • isDaemon() method checks whether thread is daemon or not.
  • setDaemon(boolean b) method makes daemon nature as non-daemon or non-daemon as a daemon if we required. by passing the value in method true or false. if we set true it makes non-daemon as daemon otherwise daemon as non-daemon.
  • setDaemon(boolean b) works fine before starting of a thread otherwise we will get a runtime exception.

Nature of Main thread is non-daemon and we can't change the behavior of main thread and other threads nature is inherited by parent or we can set by setDaemon(boolean b).

Implementation Example

In this example, we are demonstrating the behavior of setDaemon(boolean b) method​​

class DaemonThread extends Thread {

  public void run() {
    System.out.println("This thread is a daemon thread" + Thread.currentThread().isDaemon());
  }
}

class NDThread {
  public static void main(String[] args) {
    DaemonThread dt = new DaemonThread();
    System.out.println("Behaviour before setDaemon()" + dt.isDaemon());
    dt.setDaemon(true);
    dt.start();
    System.out.println("Behaviour after setDaemon()" + dt.isDaemon());
  }
}

Output

D:\Java Articles>java NDThread
Behaviour before setDaemon()false
Behaviour after setDaemon()true
This thread is a daemon threadtrue

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.