When we create a Thread in java, by default it’s a user thread and if it’s running JVM will not terminate the program. When a thread is marked as daemon thread, JVM doesn’t wait it to finish and as soon as all the user threads are finished, it terminates the program as well as all the associated daemon threads.
Thread.setDaemon(true) can be used to create a daemon thread in java. Let’s see a small example of java daemon thread.
JavaDaemonThread
package com.journaldev.threads;
public class JavaDaemonThread {
public static void main(String[] args) throws InterruptedException {
Thread dt = new Thread(new DaemonThread(), "dt");
dt.setDaemon(true);
dt.start();
//continue program
Thread.sleep(30000);
System.out.println("Finishing program");
}
}
class DaemonThread implements Runnable{
@Override
public void run() {
while(true){
processSomething();
}
}
private void processSomething() {
try {
System.out.println("Processing daemon thread");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
When we execute this program, JVM creates first user thread with main() function and then a daemon thread. When main function is finished, the program terminates and daemon thread is also shut down by JVM.
Here is the output of the above program.
Processing daemon thread
Processing daemon thread
Processing daemon thread
Processing daemon thread
Processing daemon thread
Processing daemon thread
Finishing program
If we don’t set the thread to be run as daemon thread, the program will never terminate even after main thread is finished it’s execution. Try commenting the statement to set thread as daemon thread and run the program.
Usually we create a daemon thread for functionalities that are not critical to system, for example logging thread or monitoring thread to capture the system resource details and their state.