The Daemon Thread in Java
- Keshari Abeysinghe

- Aug 7, 2020
- 1 min read
Updated: Dec 9, 2020
Daemon thread in Java provides service to the user thread which runs in the background. It is considered to be a low priority thread which is used to perform tasks such as garbage collection. In java, every thread has its priority and the one with higher priority tends to execute faster. Also, Java Virtual Machine(JVM) terminates this thread automatically. It can not prevent JVM from exiting when all the user threads finish their execution, even if daemon thread itself is running.
The major difference between a daemon thread and user thread is because of JVM. As discussed above, Java Virtual Machine does not wait for a daemon thread to finish its execution while it waits for user thread to finish.More than that daemon threads used for background tasks(not critical) and user threads used for foreground tasks(critical).The life of daemon threads depends on user threads ,but the other threads are independent
The methods used in daemon threads
public void setDaemon(boolean status)-Set thread as either a daemon thread or a user thread(non-daemon thread).
public boolean isDaemon()-Used to test if this thread is a daemon thread or not. Returns true if the thread is Daemon else false.
Below mentioned code snippet for the practical implementations
class Daemonthread extends Thread
{
public daemonthread(String name)
{
super(name);
}
public void run()
{
if(Thread.currentThread().isDaemon())
{
system.out.println(getName()+"is Daemon Thread");
}
else
{
system.out.print(getName()+"is not Daemon Thread");
}
public static void main(String[] args)
{
Daemonthread thread1= new Daemonthread("thread1");
Daemonthread thread2= new Daemonthread("thread2");
Daemonthread thread3= new Daemonthread("thread3");
thread1.setDaemon(true);
thread1.start();
thread2.start();
thread3.setDaemon(true);
thread3.start();
}
}Expected Output
thread2 is not Daemon Thread
thread1 is Daemon ThreadHappy Coding !



Comments