Daemon Threads.

How to Create Daemon Thread in Java?

  • Java
  • 3 mins read

In this tutorial, you will learn how to create Daemon Thread in Java.

What is Daemon Thread in Java?

The Java runtime environment takes advantage of a special type of thread for background tasks. It's called a daemon thread, where the daemon is pronounced "demon." These support threads manage behind-the-screen tasks like garbage collection.

Daemon threads are special because if the only threads running in the VM are daemon threads, the Java runtime will shut down or exit.

Note

When working with daemon threads in Java, be espaicially careful to remember that the daemon thread's task may be stopped in the middle of execution when the runtime shuts down.

Creating a thread as a daemon in Java is as simple as calling the setDaemon() method. A setting of true means the thread is a daemon; false means it is not. By default, all threads are created with an initial value of false.

setDaemon(boolean isDaemon)

Create Daemon Thread in Java Example

The following example we will create a daemon thread in Java which demonstrates the behavior of daemon threads. The main thread creates a daemon thread that displays a message every half second. The main thread then sleeps for five seconds. While the daemon thread is still executing, the program ends because the only currently executing threads are daemon threads.

// JavaDaemonTest.java

public class JavaDaemonTest {

    public static void main(String args[]) {
        // Create runnable action for daemon
        Runnable daemonRunner = new Runnable() {
            public void run() {
                // Repeat forever
                while (true) {
                    System.out.println("I'm a Daemon.");
                    // Sleep for half a second
                    try {
                        Thread.sleep(500);

                    } catch (InterruptedException ignored) {

                    }
                }
            }
        };
        // Create and start daemon thread
        Thread daemonThread = new Thread(daemonRunner);
        daemonThread.setDaemon(true);
        daemonThread.start();
        // Sleep for five seconds
        try {
            Thread.sleep(5000);

        } catch (InterruptedException ignored) {
        }
        System.out.println("Done.");
    }
}

Test

java JavaDaemonTest

Output

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.

It is possible that on extra "I'm Daemon." message will appear after "Done." if the timing is right (or wrong, depending upon your point of view). Were the new thread not marked as a daemon, the program would continue indefinitely until you manually stopped it. Most likely by pressing Ctrl+C.

Note

If you want a daemon java.util.Timer, pass in true to the calss constructor. Then, any scheduled tasks will be daemons.

See also: