Daemon Thread In Java
Daemon Thread
Daemon thread is a service provider, which provides the Services to the user thread. It is a low priority thread, which runs in the background to perform the tasks. Its life depends on the mercy of user threads i.e. when all the user threads dies, JVM automatically terminates this thread.
There are many Java Daemon threads running automatically such as garbage collection (gc), finalizer etc.
Important points for Daemon Thread
It provides the Services to the user threads for the background supporting tasks. It has no role in life than to serve the user threads.
Its life fully depends on the user threads.
It is a low priority thread.
JVM terminates the daemon thread if there is no user thread. Do you know why?
The main purpose of Daemon thread provides the Services to the user thread for the background supporting task due to which if there is no user thread, JVM terminates Daemon thread.
Methods for Daemon thread by Thread class
public void setDaemon(boolean status)
This method is used to mark the current thread as Daemon thread or User thread.
public boolean isDaemon()
This method is used to check whether the current thread is Daemon or not.
Let’s see an example, given below.
Code
- public class DaemonThread extends Thread {
- public void run() {
- if (Thread.currentThread().isDaemon()) { //checking for a daemon thread
- System.out.println("I am Daemon thread");
- } else {
- System.out.println("I am User thread");
- }
- }
- public static void main(String[] args) {
- DaemonThread t1 = new DaemonThread();
- DaemonThread t2 = new DaemonThread();
- t1.setDaemon(true); //it's a daemon thread
- t1.start();
- t2.start();
- }
- }
Output
If we want to create a User thread as Daemon thread, it should not be started, else it will throw an exception IllegalThreadStateException.
Let’s see an example, given below.
Code
- public class DaemonThread 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) {
- DaemonThread t1 = new DaemonThread();
- t1.start();
- t1.setDaemon(true); //throw exception
- }
- }
Output
Summary
Thus, we learnt the main purpose of Daemon thread is that it provides the Services to User thread for the background supporting task and also learnt, how to create it in Java.