Daemon Thread
Threads that run in the background are called daemon threads.
Example of Daemon Threads:
- Garbage Collector.
- Signal Dispatcher.
Objective of Daemon Thread:
The main objective of the daemon threads is to provide support to the non-daemon threads.
Additional information about Daemon Thread:
Generally, Daemon threads run in the
MIN_PRIORITY
however, it is possible to run daemon threads withMAX_PRIORITY
as well.Example: Usually the GC runs with a
MIN_PRIORITY
priority, however, once there is a requirement for additional memory. JVM increases the priority of the GC fromMIN_PRIORITY
toMAX_PRIORITY
.
Once the Thread has been started, it can't be changed from Daemon Thread to Non-Daemon Thread that will result in
IllegalThreadStateException
.Example:
public static void main(String[] args) { Thread.currentThread().setDaemon(true);}
Output:
Exception in thread "main" java.lang.IllegalThreadStateException at java.base/java.lang.Thread.setDaemon(Thread.java:1403)
If we are branching off a thread, the child thread inherits the nature of the parent thread. If the parent thread is a non-daemon thread automatically the child thread will be non-daemon as well and if the parent thread is a daemon, the child thread will be a daemon as well.
class Scratch { public static void main(String[] args) { CustomThread customThread = new CustomThread(); customThread.start(); }}class CustomThread extends Thread{ @Override public void run() { System.out.println(currentThread().isDaemon()); }}
Output:
false
When the last non-daemon thread terminates, all the daemon threads get terminated automatically.
class Scratch { public static void main(String[] args) { System.out.println("Main Thread Started."); CustomThread customThread = new CustomThread(); customThread.setDaemon(true); customThread.start(); System.out.println("Main Thread Finished."); }}class CustomThread extends Thread{ @Override public void run() { System.out.println("Custom Thread Started."); try { sleep(2000); } catch (InterruptedException ignore) {} System.out.println("Custom Thread Finished."); //Won't get executed. }}
Output:
Main Thread Started.Main Thread Finished.Custom Thread Started.