Skip to content

Java Daemon Thread

They are the silent guardians of your program, working tirelessly in the background to handle tasks that don't require your direct attention. They're like helpful spirits, quietly ensuring everything runs smoothly while you focus on more important things.

Imagine you're hosting a grand feast with guests arriving from all corners of the world. While you're busy welcoming and entertaining your guests, there's a team of invisible helpers working behind the scenes to set up tables, prepare food, and keep everything running smoothly. These helpers are your daemon threads, quietly handling tasks without disturbing the festivities.

But wait, why are they called "daemon" threads? Well, it's a nod to the concept of "daemons" in mythology—mysterious beings that dwell in the shadows and perform tasks beyond the realm of mortal understanding. In Java, daemon threads share a similar role, operating in the background and handling tasks that don't require direct human interaction.

Now, let's bring this concept to life with a simple example:

java
public class DaemonThreadExample {
    public static void main(String[] args) {
        Thread daemonThread = new Thread(() -> {
            while (true) {
                System.out.println("I'm a daemon thread doing mysterious tasks...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        daemonThread.setDaemon(true);
        daemonThread.start();

        System.out.println("Main thread: I'm busy with other things!");
    }
}

In this example, we create a daemon thread that prints a mysterious message every second. We set the thread as daemon using setDaemon(true), indicating that it should not prevent the program from exiting if the main thread finishes its execution. The daemon thread quietly continues its work in the background, even after the main thread completes its tasks.

Example

java
public class DaemonThreadExample {
    public static void main(String[] args) {
        Thread daemonThread = new Thread(() -> {
            while (true) {
                System.out.println("Daemon thread is running...");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        daemonThread.setDaemon(true); // Marking thread as daemon
        daemonThread.start();

        System.out.println("Main thread is running...");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Main thread is exiting...");
    }
}

In our example, we've created a daemon thread that prints a message every second. We've marked this thread as a daemon using setDaemon(true), indicating to the JVM that it should exit when only daemon threads are left running. Meanwhile, the main thread continues executing its tasks.

Now, let's break down what's happening:

  • We create a new thread, our daemon thread, which runs an infinite loop printing a message.
  • We mark this thread as a daemon using setDaemon(true).
  • The main thread runs alongside the daemon thread, printing its own messages.
  • After 5 seconds, the main thread finishes executing, and the JVM exits, causing the daemon thread to terminate gracefully.

Daemon threads are like background actors in a play, quietly supporting the main cast without stealing the spotlight. They're perfect for tasks like garbage collection, monitoring, or maintenance activities that should run in the background without disrupting the main flow of your program.

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.