Daemon Thread
Daemon Thread
In Java, any thread can be a Daemon thread. Daemon threads are like a service providers for other threads or objects running in the same process as the daemon thread. Daemon threads are used for background supporting tasks and are only needed while normal threads are executing.
In java we have two types of Threads: Daemon Thread and User Threads. Generally all threads created by programmer are user thread (unless you specify it to be daemon or your parent thread is a daemon thread). It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM terminates this thread automatically.
Points to remember for Daemon Thread:
It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
- Its life depends on user threads.
- It is a low priority thread.
- User thread is generally meant to run our program code. JVM doesn’t terminate unless all the user thread terminate.
On the other hand we have Daemon threads. Typically these threads are service provider threads. They should not be used to run your program code but some system code. These threads run parallel to your code but survive on the mercy of the JVM. When JVM finds no user threads it stops and all daemon thread terminate instantly. Thus one should never rely on daemon code to perform any program code.
For better understanding consider a well known example of Daemon thread: Java Garbage collector. Garbage collector runs as a daemon thread to reclaim any unused memory. When all user threads terminates, JVM may stop and garbage collector also terminates instantly.
Why JVM terminates the daemon thread if there is no user thread remaining?
The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.
Methods for Daemon thread:
The java.lang.Thread class provides two methods related to daemon thread
- public void setDaemon(boolean status): is used to mark the current thread as daemon thread or user thread.
- public boolean isDaemon(): is used to check that current is daemon.
Example of Daemon thread:
class DeamonThread extends Thread{ public void run(){ System.out.println("Name: "+Thread.currentThread().getName()); System.out.println("Daemon: "+Thread.currentThread().isDaemon()); } public static void main(String[] args){ DeamonThread t1 = new DeamonThread(); DeamonThread t2 = new DeamonThread(); t1.setName("Dinesh on Java"); t1.setDaemon(true); t1.start(); t2.start(); } }
post a comment