How to create a daemon thread in Java
What is a daemon thread?
A daemon thread is a low-priority thread whose purpose is to provide services to user threads.
Since daemon threads are only required when the user threads are operating, they do not prevent the JVM from quitting after all the user threads have completed execution.
Infinite loops, which are common in daemon threads, do not cause issues because no code (including finally blocks) is executed until all the user threads have completed execution. Therefore, daemon threads should not be used for I/O activities.
How to create daemon threads in Java
We can use the setDaemon method of the Thread class to create a daemon thread.
Syntax
public final void setDaemon(boolean on)
Parameters
on: If the value isTrue, then the current thread is marked as a daemon thread.
Return value
This method doesn’t return anything.
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);}}
Code explanation
- Lines 4-7: We create an implementation of the
Runnableinterface,runnable.runnableprints whether the current thread is a daemon thread or not with the help of theisDaemon()method. - Line 8: We create a thread,
daemonThread, with the help ofrunnable. - Line 9: We name the
daemonThreadthread"daemon-thread". - Line 10: We use the
setDaemon()method to make thedaemonThreadthread a daemon thread. - Line 11: We create another thread,
notDaemonThread, with the help ofrunnable. - Line 12: We rename the
notDaemonThreadthread"not-daemon-thread". - Lines 13-14: We use the
start()method to start thedaemonThreadandnotDaemonThreadthreads. - Line 15: We make the main thread sleep for one second.