Daemon thread in java can be useful to run some tasks in background. 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.
Daemon thread in java
When a thread is marked as daemon thread, JVM doesn’t wait it to finish to terminate the program. As soon as all the user threads are finished, JVM terminates the program as well as all the associated daemon threads.
Thread.setDaemon(true)
is used to create a daemon thread in java. This method should be invoked before the thread is started otherwise it will throw IllegalThreadStateException
.
We can check if a thread is daemon thread or not by calling isDaemon()
method on it.
Another point is that when a thread is started, it inherits the daemon status of it’s parent thread.
Daemon Thread in Java Example
Let’s see a small example of daemon thread in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
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 above daemon thread program, JVM creates first user thread with main()
method and then a daemon thread.
When main method is finished, the program terminates and daemon thread is also shut down by JVM.
Below image shows the output of the above program.
If we don’t set the “dt” thread to be run as daemon thread, the program will never terminate even after main thread is finished it’s execution. Notice that DaemonThread
is having a while true loop with thread sleep, so it will never terminate on it’s own.
Try to comment the statement to set thread as daemon thread and run the program. You will notice that program runs indefinitely and you will have to manually quit it.
Daemon Thread Usage
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. If you are not okay will a thread being terminated, don’t create it as a daemon thread.
Also it’s better to avoid daemon threads for IO operations because it can cause resource leak when program just terminates and resources are not closed properly.
Reference: API Doc