Java Daemon Thread
Contents
Java Daemon Thread :
- There are two types of threads in Java i.e User Thread and Daemon threads.
- Daemon threads runs in background and perform the background tasks
- Daemon threads are generally created by JVM
- Daemon threads are terminated by the JVM as soon as user thread finish there execution
- Daemon threads are low priority threads.
- JVM does not wait for the complete execution of daemon thread, there life is completely depends on User thread.
Daemon Methods :
Java Provides us different methods for the daemon thread -
Method | Explanation |
---|---|
void setDaemon(boolean status) | Used to set the current thread as daemon thread or user thread. |
boolean isDaemon() | Used to check whether current thread is daemon or not |
Example #1 : Setting the Daemon Thread
package com.c4learn.thread; public class DaemonThreadExample extends Thread { public void run() { String tName = Thread.currentThread().getName(); Boolean daemon = Thread.currentThread().isDaemon(); System.out.println(tName + " is daemon : " + daemon); } public static void main(String[] args) throws InterruptedException { DaemonThreadExample t0 = new DaemonThreadExample(); DaemonThreadExample t1 = new DaemonThreadExample(); t0.setDaemon(true); t0.start(); t1.start(); } }
Output :
Thread-0 is daemon : true Thread-1 is daemon : false
In the above example , we have created t0 thread as daemon thread.
IllegalThreadStateException Exception :
When we try to delete the file then primary condition of delete operation is that, file must be closed.
Similarly thread must not be started before setting it daemon otherwise it throws IllegalThreadStateException exception.
package com.c4learn.thread; public class DaemonThreadExample extends Thread { public void run() { String tName = Thread.currentThread().getName(); Boolean daemon = Thread.currentThread().isDaemon(); System.out.println(tName + " is daemon : " + daemon); } public static void main(String[] args) throws InterruptedException { DaemonThreadExample t0 = new DaemonThreadExample(); DaemonThreadExample t1 = new DaemonThreadExample(); t0.start(); t0.setDaemon(true); t1.start(); } }