In Java, any thread can be a Daemon thread. Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing.

In java we have two types of Threads: Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

Points to remember for Daemon Thread:
It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.

  • Its life depends on user threads.
  • It is a low priority thread.
  • User thread is generally meant to run our program code. JVM doesn’t terminate unless all the user thread terminate.

On the other hand we have Daemon threads. Typically these threads are service provider threads. They should not be used to run your program code but some system code. These threads run parallel to your code but survive on the mercy of the JVM. When JVM finds no user threads it stops and all daemon thread terminate instantly. Thus one should never rely on daemon code to perform any program code.

For better understanding consider a well known example of Daemon thread: Java Garbage collector. Garbage collector runs as a daemon thread to reclaim any unused memory. When all user threads terminates, JVM may stop and garbage collector also terminates instantly.

Why JVM terminates the daemon thread if there is no user thread remaining?
The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.

Methods for Daemon thread:
The java.lang.Thread class provides two methods related to daemon thread

  1. public void setDaemon(boolean status): is used to mark the current thread as daemon thread or user thread.
  2. public boolean isDaemon(): is used to check that current is daemon.

Example of Daemon thread:

class DeamonThread extends Thread{
   public void run(){
      System.out.println("Name: "+Thread.currentThread().getName());
      System.out.println("Daemon: "+Thread.currentThread().isDaemon());
   }

  public static void main(String[] args){
     DeamonThread t1 = new DeamonThread();
     DeamonThread t2 = new DeamonThread();
     t1.setName("Dinesh on Java");     
     t1.setDaemon(true);
  
     t1.start();
     t2.start();
 }
}

output:

Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.

class DeamonThread extends Thread{
   public void run(){
      System.out.println("Name: "+Thread.currentThread().getName());
      System.out.println("Daemon: "+Thread.currentThread().isDaemon());
   }

  public static void main(String[] args){
     DeamonThread t1 = new DeamonThread();
     DeamonThread t2 = new DeamonThread();
     t1.setName("Dinesh on Java");
     t1.start();     
     t1.setDaemon(true);
  
     t2.start();
 }
}

Output:

What is difference between User and Daemon Thread in Java?
Java makes a distinction between a user thread and another type of thread known as a daemon thread. The daemon threads are typically used to perform services for user threads. The main() method of the application thread is a user thread. Threads created by a user thread are user thread. JVM doesn’t terminates unless all the user thread terminate.

You can explicitly specify a thread created by a user thread to be a daemon thread by calling setDaemon(true) on a Thread object. For example, the clock handler thread, the idle thread, the garbage collector thread, the screen updater thread, and the garbage collector thread are all daemon threads. A new created thread inherits the “daemon-status” of the thread that created it unless you explicitly calling setDaemon on that Thread object to change its status.

Note that the setDaemon() method must be called before the thread’s start() method is invoked.Once a thread has started executing (i.e., its start() method has been called) its daemon status cannot be changed. To determine if a thread is a daemon thread, use the accessor method isDaemon().

The difference between these two types of threads is straightforward: If the Java runtime determines that the only threads running in an application are daemon threads (i.e., there are no user threads in existence) the Java runtime promptly closes down the application, effectively stopping all daemon threads dead in their tracks. In order for an application to continue running, it must always have at least one live user thread. In all other respects the Java runtime treats daemon threads and user threads in exactly the same manner.

<<Previous <<   || Index ||   >>Next >>

Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago