Daemon Thread

Daemon Thread

In this tutorial, we are going to discuss about Daemon Thread in java. In Java, a daemon thread is a special type of thread that runs in the background, providing services to user threads and the JVM. Unlike user threads, which are meant to perform tasks that are critical to the application’s functionality, daemon threads are typically used for supporting tasks that are less critical or auxiliary in nature.

The threads which hare running in the background to provide support for user defined threads are called “Daemon Thread”.

Daemon Thread

Here are some key characteristics of daemon threads:

  1. Background Execution: Daemon threads run in the background and are not essential to the application’s operation. They are automatically terminated when all user threads have finished executing or when the JVM is shut down, regardless of their current state of execution.
  2. Supporting Services: Daemon threads often perform tasks such as garbage collection, finalization, monitoring, and logging. They provide support to user threads and help manage various aspects of the JVM’s execution environment.
  3. Termination Upon JVM Exit: Daemon threads are automatically terminated when the JVM exits. This means that they do not prevent the JVM from shutting down, even if they are still executing. This behavior contrasts with user threads, which must complete their execution before the JVM can exit.
  4. SetDaemon Method: In Java, you can create a daemon thread by calling the setDaemon(true) method on a Thread object before starting it. By default, threads are non-daemon, so you explicitly need to mark them as daemon threads if you want them to exhibit daemon behavior.

Usually daemon thread are running with low priority but based on our requirement we can increase their priority also. The main objective of daemon Threads is to provide support for non-daemon Threads like main Thread.

E.g

Garbage collector
  • When ever the program runs with low memory the JVM will execute Garbage Collector to provide free memory. So that the main Thread can continue it’s execution.
  • We can check whether the Thread is daemon or not by using isDaemon() method of Thread class.

public final boolean isDaemon();

We can change daemon nature of a Thread by using setDaemon () method.

public final void setDaemon(boolean b);

But we can change daemon nature before starting Thread only. That is after starting the Thread if we are trying to change the daemon nature we will get R.E saying IllegalThreadStateException.

Default Nature

  • Main Thread is always non daemon and we can’t change its daemon nature because it’s already started at the beginning only.
  • Main Thread is always non daemon and for the remaining Threads daemon nature will be inheriting from parent to child that is if the parent is daemon child is also daemon and if the parent is non daemon then child is also non daemon.
  • Whenever the last non daemon Thread terminates automatically all daemon Threads will be terminated.
package com.ashok.threads;

/**
 * 
 * @author ashok.mariyala
 *
 */
class MyThread extends Thread {

}

public class MyDaemonThread {
   public static void main(String[] args) {
      System.out.println(Thread.currentThread().isDaemon());
      MyThread t = new MyThread();
      System.out.println(t.isDaemon());
      t.start();
      t.setDaemon(true);
      System.out.println(t.isDaemon());
   }
}

Output

false
false
RE:IllegalThreadStateException
package com.ashok.threads;

/**
 * 
 * @author ashok.mariyala
 *
 */
class MyThread extends Thread {
   public void run() {
      for (int i = 0; i < 10; i++) {
         System.out.println("Child thread");
         try {
            Thread.sleep(2000);
         } catch (InterruptedException e) {
         }
      }
   }
}

public class MyDaemonThread {
   public static void main(String[] args) {
      MyThread thread = new MyThread();
      thread.setDaemon(true); 
      thread.start();
      System.out.println("Main Thread");
   }
}

Output

Main Thread
Child thread

If we comment line thread.setDaemon(true); then both main & child Threads are non-Daemon, and hence both threads will be executed untill there completion.

If we are not comment line thread.setDaemon(true); then main thread is non-Daemon and child thread is Daemon. Hence when ever main Thread terminates automatically child thread will be terminated.

Note

We can call stop() method to stop a Thread in the middle then it will be entered into dead state immediately.

public final void stop();
  • stop() method has been deprecated and hence not recommended to use.
  • A Thread can suspend another Thread by using suspend() method then that Thread will be paused temporarily.
  • A Thread can resume a suspended Thread by using resume() method then suspended Thread will continue its execution.
public final void suspend();
public final void resume(); 
  • Both methods are deprecated and not recommended to use.
RACE condition

Executing multiple Threads simultaneously and causing data inconsistency problems is nothing but Race condition. We can resolve race condition by using synchronized keyword.

That’s all about the Daemon Thread in java. If you have any queries or feedback, please write us at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!

Daemon Thread
Scroll to top