Daemon Threads in Java

In this tutorial, we will learn about Daemon Threads in Java. We will see what a daemon thread is, how to create a daemon thread, various methods present for daemon threads in Thread class, usecases where we can use daemon threads and finally some of the differences between daemon and non-daemon threads.

1. Introduction

Daemon Threads are the low-priority threads that will execute in the background to provide support for the non-daemon threads (a thread that executes the main logic of the project is called a non-daemon or user thread). Daemon Threads in Java are also known as Service Provider Threads.

Let us consider a situation where the main thread is running with low memory; then what JVM will do, it will run the Garbage Collector (GC) to destroy the unreachable objects so that the memory will be freed up and with this free memory, the main thread can continue its execution. So here this GC is a daemon thread that provides the service of cleaning memory for the main thread so that the main thread can continue its execution without any interruption. Hence the main objective of daemon threads is to provide services to main/user threads.

Some examples of Daemon Threads are Garbage Collector, Signal Dispatcher, Attach Listener, Finalizer, etc.

Let us discuss some of the important properties of Daemon Threads:

  • The life cycle of daemon threads depends on user threads. It provides services to user threads for background supporting tasks.
  • They cannot prevent the JVM from exiting when all the user threads finish their execution.
  • When all the user threads terminate, JVM terminates Daemon threads automatically.
  • It is a thread with the lowest priority possible.
  • JVM won’t be concerned about whether the Daemon thread is active or not.

2. Methods for Daemon Thread

The following methods directly create or test a thread to be daemon thread.

  • void setDaemon(boolean status): To make a thread a daemon thread. We can change the nature of a thread by using this method.
  • boolean isDaemon(): Used to determine whether or not the current thread is a daemon. If the thread is Daemon, it returns true; otherwise false.

In the following example, we are creating two threads. We are marking a thread daemon and then testing both threads to be daemon or user threads.

public class Task extends Thread
{
	String threadName;

	public Task(String name){
		threadName = name;
	}

	public void run() {
		if(Thread.currentThread().isDaemon())
		{
			System.out.println(threadName + " is Daemon Thread");
		} else{
			System.out.println(threadName + " is User Thread");
		}
	}

	public static void main(String[] args)
	{
		Task thread1 = new Task("thread1");
		Task thread2 = new Task("thread2");

		// Making thread1 as Daemon
		thread1.setDaemon(true);

		thread1.start();  
		thread2.start();
	}
}
thread1 is Daemon Thread
thread2 is User Thread

We can change the daemon nature of a thread using setDaemon(), but changing the daemon nature is possible before starting a thread only. After starting a thread, if we are trying to change the daemon nature, we will get IllegalThreadStateException.

Task thread = new Task("user-thread");
thread.start(); 

thread.setDaemon(true);           // java.lang.IllegalThreadStateException

3. The Main Thread

By default, the main thread is always non-daemon, and for all the remaining threads, daemon nature inherits from parent to child i.e. if the parent thread is daemon then automatically child thread is also daemon and vice-versa.

Since the main thread is a non-daemon thread, any other thread created from it will remain non-daemon until explicitly made daemon by calling setDaemon(true) method.

It is not possible to change the daemon nature of the main thread because the main thread is already been started by JVM at the beginning. If we try to change the daemon nature of the main thread by using setDaemon() method, then it will raise IllegalThreadStateException.

class ThreadDemo {
	public static void main(String[] args){

		System.out.println(Thread.currentThread().isDaemon()); // false
		Thread.currentThread().setDaemon(true); // java.lang.IllegalThreadStateException
	}
}

4. Daemon Thread Termination

JVM terminates all the daemon threads irrespective of whether daemon threads are running or not whenever the last user thread terminates. The main purpose of a daemon thread is to provide services to the user thread for background-supporting tasks. If there is no user thread, why should JVM keep running this daemon thread? That is why JVM terminates the daemon thread if there is no user thread.

class Task extends Thread {

	public void run(){
		for(int i=0;i<10;i++){
			System.out.println("Child Thread is executing");
			try {
				Thread.sleep(2000);
			} catch(InterruptedException e){
				//...
			}
		}
	}
}

class ThreadDemo{
	public static void main(String[] args){

		Task thread = new Task();
		thread.setDaemon(true);
		thread.start();
		System.out.println("Main thread is terminating");
	}
}

Notice the output. When the main/user thread terminates, immediately the daemon thread i.e. child thread terminates as well, and it won’t complete. It’s for-loop 10 times and JVM terminates it in the middle itself.

Child Thread is executing
main thread is terminating

5. When to Use Daemon Threads?

Daemon threads are useful for background-supporting tasks such as garbage collection, releasing the memory of unused objects and removing unwanted entries from the cache.

We can use Daemon Threads in usecases like:

  • Collecting statistics and performing the status monitoring tasks – Sending and receiving network heartbeats, supplying the services to monitoring tools, and so on.
  • Performing asynchronous I/O tasks – We can create a queue of I/O requests, and set up a group of daemon threads servicing these requests asynchronously.
  • Listening for incoming connections – daemon threads are very convenient in situations like this because they let us program a simple “forever” loop rather than creating a setup that pays attention to exit requests from the main thread.

6. Difference between Daemon Thread and User Thread

Lets now collect some of the differences between daemon and non-daemon threads:

  • Creation: JVM creates Daemon threads, whereas an application creates its own user threads.
  •  Usage: Daemon threads provide service to the user threads and always run in the background, whereas user threads are used for foreground and I/O tasks of an application.
  • Priority: Daemon threads are low-priority threads, whereas user threads are of high priority.
  • JVM Behavior: JVM does not wait for daemon threads execution to complete, whereas JVM waits till the execution of the user thread is finished.
  • Life Cycle: The daemon threads’ lifecycle depends on user threads, whereas user threads have an independent lifecycle.
  • Termination: All the daemon threads are terminated once the last user thread has been terminated, irrespective of the daemon thread’s position at that time, whereas user threads are terminated after completing their corresponding jobs.

7. Conclusion

In this Java concurrency tutorial, we learned what daemon threads are and how we can utilize them in a few real applications. We have also learned the main methods in Thread class to work with daemon threads and some of the main differences between daemon and non-daemon threads.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode