Daemon Thread in Java with Example
Daemon thread in Java is a service thread that provides some services to other threads or objects. It executes continuously without any interruption to provide services to one or more user threads.
It typically runs in the background. Once the daemon thread started, it continues to provide that service until the application terminates. Its termination is automatic.
For example, oracle.exe is an application program (a thread) that continuously runs on a computer. When the computer is switched on, it also starts running and will end only when the computer is turned off. Any other thread like SQL+ can communicate with it to retrieve or store data.
Other examples are garbage collector, finalizer, housekeeping, etc are java daemon threads that run automatically.
The garbage collector of JVM process always runs in the background for freeing memory of unused objects. If the garbage collector is only thread running, JVM does not continue the execution process and it exits.
Key Points to Remember for Daemon Thread
1. Daemon thread has no other role in life rather than to serve user threads.
2. Since the life span of daemon thread depends on the user thread, therefore, it provides services to user threads in the background as long as the program is running.
3. Daemon thread is a low-priority thread.
4. Java supports two general types of threads: user threads (normal threads) and daemon threads. The difference between two is that a user thread will continue to execute until its run() method ends while a daemon thread will be automatically ended when all user threads of a program have ended.
5. If only daemon thread is running a program and all user threads have completed their execution, JVM will exit from the program because daemon thread will be ended automatically.
How to Create Daemon Thread in Java?
Thread class provides two methods to create and use daemon thread in a Java program.
1. isDaemon(): This method is used to check the status (state) of a particular thread. It returns true if a thread is a daemon otherwise returns false. The general syntax to use this method is as follows:
Syntax:
final boolean isDaemon()
2. setDaemon(): This method is used to make a user thread to daemon thread and vice versa. It is used to change daemonic state of a thread. The general syntax for this method is as follows:
Syntax:
final void setDaemon(boolean)
It takes a boolean value as an argument. If it is true, then the thread will be set to a daemon. If it is false, then the thread will be set to the user. The setDaemon() method must be called before calling start() method otherwise it will throw an exception named IllegalThreadStateException.
For example, suppose we have a user thread t. To make a thread t as a daemon thread, just call setDaemon() after the creation of a thread and before the execution is started. The following two statements are to make a thread as a daemon.
Thready t = new Thread();
t.setDaemon(true);
Daemon Thread Example Programs
Let’s take a simple example program to demonstrate a daemon thread.
Example 1:
public class MyDaemon implements Runnable {
public void run()
{
// Checking whether a thread is Daemon or not.
if(Thread.currentThread().isDaemon()) {
System.out.println(Thread.currentThread() + " is a daemon thread");
}
else {
System.out.println(Thread.currentThread() + " is a user (normal) thread");
}
}
public static void main(String[] args)
{
MyDaemon obj = new MyDaemon();
Thread t1 = new Thread(obj, "Thread 1");
t1.setDaemon(true); // Set to daemon.
Thread t2 = new Thread(obj, "Thread 2");
t1.start(); // Execution starts.
t2.start();
System.out.println("Main thread ending");
}
}
Output: Main thread ending Thread[Thread 1,5,main] is a daemon thread Thread[Thread 2,5,main] is a user (normal) thread
Let’s take another example program where we will call the setDaemon() method after starting a thread (i.e. before start() method is called) and it will throw IllegalThreadStateException. Look at the source code to understand better.
Example 2:
public class MyDaemon implements Runnable {
public void run()
{
System.out.println(Thread.currentThread() + " is a daemon thread");
}
public static void main(String[] args)
{
MyDaemon obj = new MyDaemon();
Thread t1 = new Thread(obj, "Thread 1");
t1.start(); // Execution starts.
t1.setDaemon(true); // It will throw IllegalThreadStateException.
System.out.println("Main thread ending");
}
}
Output: Exception in thread "main" Thread[Thread 1,5,main] is a daemon thread java.lang.IllegalThreadStateException at java.lang.Thread.setDaemon(Unknown Source) at thread11.MyDaemon.main(MyDaemon.java:15)
In this example program, we have called setDaemon() method after the start() method is called. Therefore, it threw IllegalThreadStateException.
In this tutorial, we have covered all the important topics related to daemon thread in Java with the help of example programs. I hope that you will have understood this simple topic and enjoyed it.
If you get any incorrect in this tutorial, please inform us through email. Your email will be valuable to us. In the next, we will learn about the volatile keyword in Java with examples.
Thanks for reading!!!