Thread Java 30 days- day 8 (Daemon)

paul chou
2 min readAug 16, 2023

--

Today we are going to introduce Daemon Threads.

In Java, there are two types of threads: User Threads and Daemon Threads.

A Daemon Thread refers to a background thread that provides general services while the program is running. For example, the garbage collection thread is a well-behaved daemon, and such threads are not considered essential parts of the program. As a result, when all non-daemon threads terminate, the program also terminates, along with killing all daemon threads within the process. Conversely, as long as any non-daemon thread is still running, the program will not terminate.

There is very little disinction between user threads and daemon threads. The only difference lies in the behavior of the virtual machine: if all user threads have exited,leaving only daemon threads, the virtual machine will exit as well. This is because daemon threads have no purpose to continue running without non-daemon threads to serve.

You can convert a thread into a daemon thread by calling the setDaemon(true) method on the Thread object. When using daemon threads, consider the following points:

  1. thread.setDaemon(true) must be before thread.start(), otherwise it will throw an “IllegalThreadStateException”. You cannot set a running regular thread to a daemon thread.
  2. Threads created within a Daemon thread are also Daemon threads
  3. Daemon threads should never access intrinsic resources like files or database, as they can be interrupted at any time, even in the middle of an operation.
public class DaemonExample{
public static void main(String[] args){
Thread daemonThread = new Thread(new DaemonTask());
daemonThread.setDaemon(true);
daemonThread.start();

for(int i = 0; i < 3; i ++){
System.out.println("Main thread working...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

static class DaemonTask implements Runnable{
@Override
public void run(){
while(true){
System.out.println("Daemon thread running...");
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

}
}

--

--