Daemon Thread
Daemon thread is a low priority thread in JVM. It runs in the background to perform tasks such as garbage collection.
Such daemon threads do not prevent the JVM from exiting even when they are running.
JVM terminates itself when all user threads finish their execution. JVM does not bother even if Daemon threads are running.
If after completion of user threads, JVM finds one or more daemon threads running, it terminates those daemon threads and shuts down itself.
Properties of daemon threads
- A newly created thread inherits the status of its parent thread, thread that created it. That’s why all the threads created inside main method have their status as non-daemon by default. Simply because main thread is non-daemon. But having said that, we can make a user thread daemon by calling setDaemon() method on it.
- Using setDaemon(boolean status) method on a thread, we can make it daemon or non-daemon by passing true and false respectively. Using isDaemon() method, we can check whether a thread is daemon or not.
- We must remember that we have to call setDaemon() method on a thread before starting it. Otherwise, it will throw IllegalThreadStateException.
Daemon Thread Example
package com.javatrainingschool;
public class DaemonThreadExample implements Runnable {
public void run() {
if (Thread.currentThread().isDaemon()) {
System.out.println(Thread.currentThread().getName() + " : Daemon thread running");
} else {
System.out.println(Thread.currentThread().getName() + " : User thread running");
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new DaemonThreadExample(), "Thread-1");
Thread t2 = new Thread(new DaemonThreadExample(), "Thread-2");
t1.setDaemon(true);
t1.start();
t2.start();
}
}
Output :
Thread-1 : Daemon thread running
Thread-2 : User thread running
Calling setDaemon() method after the thread is started
It will throw exception if setDaemon() method is called after the thread is started. It doesn’t matter whether you are making a user thread daemon or a daemon thread non-daemon. If you are calling setDaemon() method after the thread is started, IllegalThreadStateException is thrown.
package com.javatrainingschool;
public class DaemonThreadExample implements Runnable {
public void run() {
if (Thread.currentThread().isDaemon()) {
System.out.println(Thread.currentThread().getName() + " : Daemon thread running");
} else {
System.out.println(Thread.currentThread().getName() + " : User thread running");
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new DaemonThreadExample(), "Thread-1");
t1.start();
t1.setDaemon(true);
}
}
Output :
Exception in thread "main" Thread-1 : User thread running
java.lang.IllegalThreadStateException
at java.lang.Thread.setDaemon(Thread.java:1359)
at com.javatrainingschool.DaemonThreadExample.main(DaemonThreadExample.java:19)