Daemon Threads


Daemon Threads

What is a daemon thread?

Every thread in a process, aside from its state, is prioritised where threads with higher priority are executed in preference to lower priority threads. Daemon threads run in the background and are low priority operations.

The setDaemon() method of the Thread class is used to mark a thread as either a daemon thread, or a user thread.

Some of the common uses for daemon threads are: 
  • Garbage collectors (Collecting statistics and status monitoring tasks)
  • Performing asynchronous input, output tasks. 
  • Listening for incoming connections

Creating a Daemon Thread

Creating a daemon thread is pretty simple, we make use of the setDaemon() method (line 18).
When the parameter is true, we declare that the thread is a daemon thread. 
By default, the parameter is set to false, which means the thread is a normal / user thread.

In the example below, the main thread creates a daemon thread that displays "I'm a Daemon." every 0.5 seconds. Our main thread will rest for 5 seconds. 

While the program is displaying "I'm a Daemon.", the main program ends because the only thread(s) running are daemon threads.

 1  public class DaemonThreadExample {
2
3 public static void main(String[] args) {
4 // Create runnable action for daemon
5 Runnable daemonRunner = () -> {
6 // Repeat forever
7 while (true) {
8 System.out.println("I'm a Daemon.");
9 // Sleep for half a second
10 try {
11 Thread.sleep(500);
12 } catch (InterruptedException ignored) {
13 }
14 }
15 };
16 // Create and start daemon thread
17 Thread daemonThread = new Thread(daemonRunner);
18 daemonThread.setDaemon(true);
19 daemonThread.start();
20 // Sleep for five seconds
21 try {
22 Thread.sleep(5000);
23 } catch (InterruptedException ignored) {
24 }
25 System.out.println("Done.");
26 }
27 }
I'm a Daemon.
I'm a Daemon.
I'm a Daemon.
I'm a Daemon.
I'm a Daemon.
I'm a Daemon.
I'm a Daemon.
I'm a Daemon.
I'm a Daemon.
I'm a Daemon.
Done.

Comments

Popular posts from this blog