Daemon Thread
Daemon thread is a special type of thread that runs in background and performing background task for user defined threads like Garbage Collection.
Daemon threads are low priority threads. If all the user defined threads or main thread of an application ends then JVM Will exit by killing all the daemon threads that are left. JVM does not wait for a daemon thread to finish its execution.
In other words we can say that thread which has no exit mechanism is called Daemon thread.
Daemon nature is inherited from parent, If parent is daemon thread then its child also will be a daemon thread.
How to create daemon thread
By default , a thread is non-daemon thread,
A user created thread can be converted to daemon thread by calling setDaemon(true).
setDaemon(boolean) method is called before start() method of thread is called by JVM. Daemon status cannot be changed if thread start() method is invoked.
To check whether the thread is daemon thread or not use the method isDaemon() ,This method returns true if thread is daemon otherwise it returns false.
Important points for Daemon thread
a) setDaemon(boolean) is called before starting Thread in Java otherwise it will throw IllegalThreadStateException .
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.j2eereference.coreJava; class test1 extends Thread { public static void main(String args[]) { test1 t=new test1(); t.start(); t.setDaemon(true); //System.out.println(t.asDaemon()); } } |
Run the above code you will get “Exception in thread “Main Thread” java.lang.IllegalThreadStateException”.
b)Thread which is created by main thread, is non daemon thread as daemon nature is inherit by parent so any other thread created from it is non-daemon until we make it daemon thread by calling setDaemon(true) explicitly .So, when a new thread is created it inherits the daemon status of its parent.
Example of Daemon Thread
Consider the following example that demonstrate how daemon thread is created.
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.j2eereference.coreJava; public class DaemonThread extends Thread { public static void main(String[] args) { DaemonThread t = new DaemonThread (); //setting the thread as a daemon thread t.setDaemon(true); t.start(); } |
1 2 3 4 5 6 7 |
public void run(){ System.out.println("This is an example of Daemon Thread."); } } |
Output is:
This is an example of Daemon Thread.
Leave a Reply