What is the Daemon Thread in Java?

  • The thread executing in the running program’s background is called the daemon thread in Java.
  • The garbage collector is one example of Daemon Thread in java.
  • They are used to provide support for non-daemon threads in java.
  • Example: If the main thread runs with low memory then JVM runs the garbage collector to destroy the useless objects and free some memory.
  • Usually, this threads run with low priority but based on our requirement daemon threads can also run with high priority.
  • We can check if a thread is a daemon or not by using the isDaemon() method.
  • We can set any thread as a daemon thread using the setDaemon(boolean b) method.
  • Changing the daemon nature is possible before starting a thread else we will get Runtime Exception as IllegalThreadStateException.

Let’s see the example below for Daemon Thread in Java. (Output sequence for the following program can be different)

Java Code
class Test {
static int i = 0;
public static void main(String args[]) throws InterruptedException {
DaemonThread d = new DaemonThread();
MyThread t = new MyThread();

d.setDaemon(true);

System.out.println(“–Is demonThread d: ” + d.isDaemon());
System.out.println(“–Is demonThread t: ” + t.isDaemon());

d.start();
t.start();

Thread.currentThread().sleep(500);
System.out.println(Test.i);
}
}

class DaemonThread extends Thread {
public void run() {
while(true) {
Test.i = Test.i + 1;
}
}
}

class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(“Running MyThread ” + i);
}
}
}

Output:
–Is demonThread d: true
–Is demonThread t: false
Running MyThread 0
Running MyThread 1
Running MyThread 2
Running MyThread 3
Running MyThread 4
1069550001
  • By default, the main thread is always a non-daemon thread.
  • For remaining all threads daemon nature will be inherited from parent to child. That is if a parent is a daemon thread then a child is also a daemon.
  • It’s impossible to change the daemon nature of the main thread since it is already stated by JVM at the beginning. After starting the thread daemon nature can not be changed.
  • Whenever the last non-daemon thread is terminated automatically all daemon threads will be terminated irrespective of their position.

How to Stop a Thread?

  • By using the stop() method of the Thread class we can stop the execution of the Thread. This method is deprecated.
    • Syntax: public final void stop()
  • Thread immediately enters into a dead state after the stop method.
  • Since this method is deprecated it’s not recommended to use.

How to suspend & resume a Thread?

  • A thread can suspend another thread by using the suspend() & resume by using the resume() method of thread class. 
    • Syntax for suspend: public final suspend void suspend();
    • Syntax for resume: public final void resume();

-A blog by Shwetali Khambe

Related Posts