Java Daemon Thread
In this tutorial, we will learn about Java daemon threads, along with working example, major benefits of it and differences from daemon to normal threads.
What is a daemon thread
In Java, a daemon thread is a type of thread that runs in the background, which provides support for other normal threads and tasks and daemon threads are different from a regular thread in that it does not prevent the JVM from being shut down when all non-daemon threads have completed their execution.
In other words, when all non-daemon threads have completed their execution then JVM will terminate the daemon threads abruptly, without allowing them to complete their tasks.
Importance of daemon threads
- Daemon threads are typically used to perform background tasks, such as garbage collection, log file maintenance, and other maintenance tasks that do not require user interaction.
- Daemon threads can also be used to provide support for other threads and tasks. For example, a daemon thread can be used to monitor the progress of a long-running task and update a progress bar or other user interface element.
Example of daemon thread:
We can follow the same steps as we follow for normal thread creations except before starting thread make a daemon flag by invoking setDaemon method of Thread class.
public class DaemonThreadExample {
public static void main(String[] args) {
//Creating a Thread class reference passing Daemon thread reference
Thread daemonThread = new Thread(new DaemonThreadTask());
//Important step to make to daemon, need to be done before starting
daemonThread.setDaemon(true);
daemonThread.start();
System.out.println("Main thread exiting");
}
}
class DaemonThreadTask implements Runnable {
public void run() {
while(true) {
System.out.println("Daemon thread running");
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
Output:
Main thread exiting
Daemon thread running
Explanation:
Created a Thread class reference by passing Daemon Thread reference, daemon thread class implemented a Runnable interface and invoked setDaemon method to make daemon flag to true. Started a daemon thread, inside run method of Daemon thread written an infinite while loop and goes 1s sleep for every iteration.
After executing the example although Daemon thread still executing after completing main thread execution, JVM terminated Daemon thread and got a shutdown.
Conclusion:
In this tutorial, we have learned about What is daemon threads in Java, use cases of those along with the working example of it.