Threads which are running in background to provide support to “main” thread are called Daemon thread.
Daemon thread example: Garbage collector, signal dispatcher etc.
When main thread runs with low memory problem then JVM runs Garbage collector to destroy useless objects. So that memory get improve and main thread can continue.
How to check thread is Daemon or not?
Below method is use to check current thread is Daemon or not.
1 |
Thread.currentThread().isDaemon(); |
isDaemon() method returns boolean value. IF current thread is not Daemon then it will return false.
1 2 3 4 5 6 |
public class Main { public static void main(String[] args) { System.out.println(Thread.currentThread().isDaemon()); } } |
Output:
1 |
false |
As current working thread is “main” which is always non-daemon. That’s why false is answer.
How to set a thread as Daemon
We can change nature of thread using below method.
1 |
setDaemon(true); |
We can set non-Daemon thread to daemon and daemon to non daemon. But changing nature of a thread is possible before starting of a thread only.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class MyThread extends Thread { } public class Main { public static void main(String[] args) { //current thread is main which is non-daemon System.out.println(Thread.currentThread().isDaemon()); MyThread t=new MyThread(); //daemon nature will inherit from parent to child System.out.println(t.isDaemon()); //setting child thread t daemon t.setDaemon(true); System.out.println(t.isDaemon()); } } |
Output:
1 2 3 |
false false true |
If we try to change nature of a thread after starting we will get Runtime Exception: IllegalThreadStateException.
We can not change nature of “main” thread because it is already started by JVM.
1 2 3 4 5 6 7 8 9 |
public class Main { public static void main(String[] args) { System.out.println(Thread.currentThread().isDaemon()); Thread.currentThread().setDaemon(true); System.out.println(Thread.currentThread().isDaemon()); } } |
Output:
1 2 3 4 |
false Exception in thread "main" java.lang.IllegalThreadStateException at java.lang.Thread.setDaemon(Thread.java:1359) at Main.main(Main.java:10) |
Default nature of Thread
By default main thread is always non-daemon and all remaining threads nature will inherited from parent to child. That means if parent is daemon, child thread will also be daemon.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class MyThread extends Thread { } public class Main { public static void main(String[] args) { System.out.println(Thread.currentThread().isDaemon()); MyThread t=new MyThread(); //daemon nature will inherit from parent to child System.out.println(t.isDaemon()); } } |
Output:
1 2 |
false false |
Whenever last non-Daemon thread terminates automatically all daemon thread will terminate irrespective of there position.