How to check if a thread is a daemon thread
Overview
Daemon threads are low-priority threads whose purpose is to provide services to user threads.
Daemon threads are only required while user threads are operating. They will not prevent the JVM from quitting after all user threads complete their execution.
Infinite loops, common in daemon threads, do not cause issues since no code, including final blocks, will be executed until all user threads have completed their execution. As a result, daemon threads should not be used for I/O activities.
The isDaemon() method of the Thread class is used to check if a given thread is a daemon thread or not.
Syntax
public final boolean isDaemon()
Parameters
The method has no parameters.
Return value
The method returns true if the current thread is a daemon thread. Otherwise, it returns false.
Code
public class Main{public static void main(String[] args) throws InterruptedException {Runnable runnable = () -> {if(Thread.currentThread().isDaemon()) System.out.println(Thread.currentThread().getName() + " is a daemon thread");else System.out.println(Thread.currentThread().getName() + " is not a daemon thread");};Thread daemonThread = new Thread(runnable);daemonThread.setName("daemon-thread");daemonThread.setDaemon(true);Thread notDaemonThread = new Thread(runnable);notDaemonThread.setName("not-daemon-thread");daemonThread.start();notDaemonThread.start();Thread.sleep(1000);}}
Explanation
- Lines 4 to 7: We create an implementation of the
Runnableinterface, that is, arunnablethat prints whether the current thread is a daemon thread or not with the help of theisDaemon()method. - Line 8: We create a thread with the help of a
runnablecalleddaemonThread. - Line 9: We name the
daemonThreadthread asdaemon-thread. - Line 10: We make the
daemonThreadthread a daemon thread using thesetDaemon()method. - Line 11: We create another thread with the help of a
runnablecallednotDaemonThread. - Line 12: We name the
notDaemonThreadthread as"not-daemon-thread". - Lines 13 and 14: We start the threads
daemonThreadandnotDaemonThreadusing thestart()method. - Line 15: The main thread is made to sleep for one second.