Trusted answers to developer questions

How to create a daemon thread in Java

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

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 is True, 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 Runnable interface, runnable. runnable prints whether the current thread is a daemon thread or not with the help of the isDaemon() method.
  • Line 8: We create a thread, daemonThread, with the help of runnable.
  • Line 9: We name the daemonThread thread "daemon-thread".
  • Line 10: We use the setDaemon() method to make the daemonThread thread a daemon thread.
  • Line 11: We create another thread, notDaemonThread, with the help of runnable.
  • Line 12: We rename the notDaemonThread thread "not-daemon-thread".
  • Lines 13-14: We use the start() method to start the daemonThread and notDaemonThread threads.
  • Line 15: We make the main thread sleep for one second.

RELATED TAGS

java
Did you find this helpful?