Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Daemon threads are background threads in a program that handle tasks like garbage collection or supporting user threads. They run at low priority and don't prevent the program from exiting if all user threads have finished.
The sole purpose of a daemon thread is to offer services to user threads for assisting/helping the processes running in the background.
In this blog, we are going to learn about the daemon thread and its examples in detail.
What is Daemon Thread in Java?
The daemon thread is a service provider thread that offers services to users. It is a low-priority thread responsible for background processes such as garbage collection, finalizers, Action Listeners, and so on. Its ability to survive relies on user threads, and the JVM will terminate it when all user threads have expired.
Properties of Daemon Thread in Java
Below are some of the properties of the daemon thread:
It has the lowest priority possible.
If the JVM discovers a daemon thread running, it kills it and shuts it.
Once all user threads have finished their work, the daemon thread cannot prevent the JVM from terminating.
JVM shuts down after all user threads have completed running.
Whether the daemon thread is active or inactive is unimportant to the JVM.
JVM terminates the daemon thread whenever he encounters no user threads.
Daemon threads are created before user threads are created and die after all other user threads die.
Default Nature of Daemon Thread
The main thread is always non-daemon by default, but all the other threads will inherit their daemon characteristics from their parents. In other words, if a parent is a daemon, the child will likewise be a daemon, and if a parent is not a daemon, the child will also be a non-daemon.
One point to note is that all the daemon threads will be terminated automatically whenever the last non-daemon thread is terminated.
Methods of Daemon Thread
1. void setDaemon(boolean status):
This method involves designating the current thread either as a daemon or user thread. You can designate a user thread as a daemon using 'tU.setDaemon(true)', and conversely, you can designate a daemon thread as a user thread using 'tD.setDaemon(false)'
Syntax:
public void setDaemon(boolean status)
Parameters:
status (boolean): This parameter specifies whether the thread should be set as a daemon or a user thread. If true, the thread is set as a daemon thread; if false, the thread is designated as a user thread.
Exceptions:
This method must be called before the thread starts, that is, before invoking the start() method on the thread.
If you attempt to set the daemon status of a thread after it has already started, an IllegalThreadStateException will be thrown.
2. boolean isDaemon():
Utilized for verifying the current thread's daemon status, this method returns 'true' if the thread is a daemon and 'false' otherwise.
Syntax:
public boolean isDaemon()
Returns:
If the current thread is a daemon thread, the method returns true; otherwise, it returns false.
Code:
Java
Java
public class IsDaemonExample { public static void main(String[] args) { Thread currentThread = Thread.currentThread(); System.out.println("Is the current thread a daemon thread? " + currentThread.isDaemon()); Thread daemonThread = new Thread(() -> { System.out.println("Daemon thread isDaemon: " + Thread.currentThread().isDaemon()); }); daemonThread.setDaemon(true); Thread userThread = new Thread(() -> { System.out.println("User thread isDaemon: " + Thread.currentThread().isDaemon()); }); daemonThread.start(); userThread.start(); try { daemonThread.join(); userThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Main thread isDaemon: " + currentThread.isDaemon()); } }
You can also try this code with Online Java Compiler
Is the current thread a daemon thread? false
Daemon thread isDaemon: true
User thread isDaemon: false
Main thread isDaemon: false
Example of Daemon Thread in Java
Examples of daemon threads in Java consist of garbage collection (gc) and finalizer.
When a program invokes the start() function, it creates a new thread and then calls the run() method. These methods are helpful whenever we want to create a thread.
Let's now look at an example to understand the two methods of the daemon thread in Java.
Java
Java
class DaemonThreadExample extends Thread{ String name; // Constructor public DaemonThreadExample(String name){ this.name = name; }
// Calling the run method public void run(){ // Checking whether the thread is Daemon or not if (!Thread.currentThread().isDaemon()){ System.out.println(this.name + " is User thread"); } else{ System.out.println(this.name + " is Daemon thread"); } }
public static void main(String[] args){
// Creating objects DaemonThreadExample T1 = new DaemonThreadExample("First"); DaemonThreadExample T2 = new DaemonThreadExample("Second");
// Setting user thread T1 to Daemon T1.setDaemon(true);
// Starting first two threads T1.start(); T2.start(); } }
You can also try this code with Online Java Compiler
In the above code of the daemon thread, the objects T1 and T2 are created with a default type, i.e., User thread. Once we call the setDaemon() method on the T1 object, it will change its type from a user thread to a daemon thread.
Exceptions in Daemon Thread
Below are some exceptions that can occur while using the daemon thread:
Sr no
Exception
Description
1
IllegalThreadStateException
If you call the setDeamon() method when the thread is in the running state, it will throw an exception
2
SecurityException
If the current thread is not able to change this thread
Example:
Let’s now see an example to understand one of the examples of demon thread exceptions.
Java
Java
class DaemonThreadExample extends Thread{ String name; public DaemonThreadExample(String name){ this.name = name; }
public void run(){ // Checking whether the thread is Daemon or not if (!Thread.currentThread().isDaemon()){ System.out.println(this.name + " is User thread"); } else{ System.out.println(this.name + " is Daemon thread"); } }
public static void main(String[] args){
DaemonThreadExample T1 = new DaemonThreadExample("First"); DaemonThreadExample T2 = new DaemonThreadExample("Second");
// Starting thread T1 T1.start(); /* Setting user thread T1 to Daemon will get an error at this line as the thread is already running */ T1.setDaemon(true); } }
You can also try this code with Online Java Compiler
In the above code of the daemon thread, we tried to set object T1 as a daemon thread. But as the object T1 was already put in a running state using the start() method. We encountered an error stating that the thread's state is not valid to perform that action.
Daemon Thread Vs User Thread
Now, let’s see the difference between a daemon thread and a user thread.
User Thread
Daemon Thread
These are high-priority threads.
These are low-priority threads.
User threads are also referred to as foreground threads.
Daemon threads are called background threads.
JVM waits till the user thread completes its work.
JVM does not wait for the daemon thread to complete its execution.
User threads are designed for some specific tasks.
Daemon threads are designed to support the user threads.
Its life is independent.
Its life depends on the user thread.
User threads are created by the application.
The JVM generally creates daemon threads.
JVM will not force user threads to terminate.
JVM will force the daemon thread to terminate whenever all user threads are done with their tasks.
Frequently Asked Questions
Why is the daemon thread used?
Daemon threads are used for background tasks that don't prevent the program from exiting. They terminate when all non-daemon threads finish.
What is a daemon thread?
A daemon thread is a background thread that runs without blocking the program's termination.
What is difference between user thread and daemon thread?
User threads are foreground threads initiated by the user, while daemon threads are background threads that support user threads.
What is the difference between daemon and regular thread?
Daemon threads terminate when the program exits, while regular threads don't.
Can we stop daemon thread?
Yes, daemon threads can be stopped, but they automatically terminate when the program exits.
Conclusion
This article discusses the topic of daemon threads in Java. We also discussed various methods in the daemon thread and some exceptions which we may encounter while using them. We hope this blog has helped you enhance your knowledge of daemon threads. If you want to learn more, then check out our articles.
But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problems, interview experiences, and interview bundles for placement preparations.
However, you may consider our paid courses to give your career an edge over others!