Question

Daemon Threads in Java: Definition, Lifecycle, and Examples

javamultithreading

Question

Can someone explain what daemon threads are in Java, how they behave when an application exits, and when they should be used?

Short Answer

By the end of this page, you will understand that a daemon thread is a background Java thread that does not keep the JVM running. You will learn how daemon threads differ from user threads, how to create them, and why they are not suitable for work that must finish reliably.

Concept

A daemon thread is a background thread that provides supporting work for an application rather than its primary purpose.

The Java Virtual Machine (JVM) continues running while at least one user thread is alive. When every user thread has finished, the JVM can shut down—even if daemon threads are still running. At that point, daemon threads may be stopped without completing their remaining work.

Java commonly uses daemon threads internally for supporting tasks such as garbage collection. Your application can create daemon threads too, but they are best reserved for optional background work.

Important rules:

  • A normal thread is a user thread by default.
  • The main thread is a user thread.
  • A daemon thread does not prevent the JVM from exiting.
  • You must call setDaemon(true) before starting the thread.
  • A thread created by another thread normally inherits its creator's daemon status.
  • Do not use daemon threads for work that must be saved, closed, or completed, such as writing important data to a file or database.

Mental Model

Think of a Java program as an office.

  • User threads are employees doing the office's essential work. The office stays open while any employee is still working.
  • Daemon threads are background services, such as music playing or a screen displaying the time. They are useful while the office is open, but they do not decide whether the office stays open.

When the last employee leaves, the office closes immediately. The background services may be turned off in the middle of their work. In the same way, the JVM may stop daemon threads when no user threads remain.

Take Quiz

Syntax and Examples

Create a Thread, mark it as a daemon, and then start it:

Thread backgroundThread = new Thread(() -> {
    while (true) {
        System.out.println("Background work");

        try {
            Thread.sleep(1_000);
        } catch (InterruptedException exception) {
            Thread.currentThread().interrupt();
            return;
        }
    }
});

backgroundThread.setDaemon(true); // Must happen before start()
backgroundThread.start();

setDaemon(true) marks the thread as a daemon. Once start() is called, Java begins executing the lambda expression in a separate thread.

Here is a complete example:

public class DaemonExample {
    public static void main(String[] args) throws InterruptedException {
        Thread statusReporter = new Thread(() -> {
            while (true) {
                System.out.println("Daemon: application is still running");

                try {
                    Thread.sleep(500);
                } catch (InterruptedException exception) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        });

        statusReporter.setDaemon(true);
        statusReporter.start();

        Thread.sleep(1_500);
        System.out.println("Main thread is ending.");
    }
}

After main finishes, there are no user threads left. The JVM exits, so the daemon thread stops even though its while (true) loop has no normal ending condition.

Step by Step Execution

Consider this program:

public class DaemonTrace {
    public static void main(String[] args) throws InterruptedException {
        Thread helper = new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                System.out.println("Helper step " + i);

                try {
                    Thread.sleep(1_000);
                } catch (InterruptedException exception) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        });

        helper.setDaemon(true);
        helper.start();

        Thread.sleep(2_200);
        System.out.println("Main work is complete.");
    }
}

Execution flow:

  1. The JVM starts the user thread named main.
  2. main creates helper, but it is not running yet.
  3. helper.setDaemon(true) marks helper as a daemon thread.
  4. helper.start() schedules the helper code to run concurrently with main.
  5. The helper may print Helper step 1, Helper step 2, and Helper step 3 while main sleeps.
  6. After about 2.2 seconds, main prints Main work is complete.
  7. The main method returns. Since helper is only a daemon thread, no user threads remain.
  8. The JVM exits. The helper will not necessarily print all ten steps.

Real World Use Cases

Daemon threads are appropriate when their work is helpful but disposable at application shutdown.

Examples include:

  • Cache cleanup: Periodically remove expired values from an in-memory cache.
  • Metrics sampling: Collect temporary runtime statistics while a server is running.
  • Background monitoring: Check memory usage or queue sizes and log diagnostic information.
  • UI helper work: Update a non-essential visual indicator while a desktop application is open.
  • Development tools: Run optional progress indicators or local debugging helpers.

Avoid daemon threads for:

  • Writing payments, orders, or audit records.
  • Saving user documents.
  • Closing important resources that must be flushed.
  • Completing API requests or sending messages that must be delivered.

For important work, use user threads, managed executor services, queues, and explicit shutdown handling.

Take Quiz

Real Codebase Usage

In production code, developers often avoid manually creating raw threads. Instead, they use ExecutorService or ScheduledExecutorService to manage background tasks.

A daemon thread factory can make executor-created threads daemon threads:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

public class DaemonScheduler {
    public static void main(String[] args) {
        ThreadFactory daemonFactory = runnable -> {
            Thread thread = new Thread(runnable, "cache-cleanup");
            thread.setDaemon(true);
            return thread;
        };

        ScheduledExecutorService scheduler =
                Executors.newSingleThreadScheduledExecutor(daemonFactory);

        scheduler.scheduleAtFixedRate(
                () -> System.out.println("Removing expired cache entries"),
                0,
                30,
                TimeUnit.SECONDS
        );

        System.out.println("Application started");
    }
}

Common project patterns:

  • Use daemon threads for optional maintenance tasks.
  • Name threads so logs and thread dumps are easier to read.
  • Catch and handle exceptions inside long-running tasks; an uncaught exception ends that task.
  • Use try-with-resources or explicit shutdown for resources that must be closed.
  • Use shutdown() and awaitTermination() for executor tasks that must complete before the application ends.

If shutdown correctness matters, design it explicitly rather than relying on daemon-thread termination.

Common Mistakes

Setting daemon status after starting a thread

This is invalid:

Thread thread = new Thread(() -> System.out.println("Working"));
thread.start();
thread.setDaemon(true); // Throws IllegalThreadStateException

Set the daemon status before calling start():

thread.setDaemon(true);
thread.start();

Expecting a daemon thread to finish

This code may never write the message because main ends immediately:

Thread thread = new Thread(() -> System.out.println("Save important data"));
thread.setDaemon(true);
thread.start();

Use a user thread or wait for important work to finish instead.

Using daemon threads to save critical data

A daemon thread may be stopped during file writing, network communication, or database work. Use explicit lifecycle management for critical operations.

Assuming finally will always run at JVM exit

When the JVM exits because only daemon threads remain, it does not wait for those threads to finish normally. Do not depend on a daemon thread's finally block for essential cleanup.

Confusing daemon threads with the operating system's daemons

A Java daemon thread is a JVM thread classification. It is not the same thing as an operating-system service or a server process that runs independently in the background.

Comparisons

FeatureUser threadDaemon thread
Default for new Thread(...)YesNo
Keeps the JVM aliveYesNo
Suitable for essential workYesNo
May be abandoned when JVM exitsNo, the JVM waits for itYes
Example useProcessing an API requestOptional cache cleanup

Daemon thread vs executor service

ChoiceBest for
Thread with setDaemon(true)A small, simple background task or learning example
ExecutorServiceManaging several tasks, controlling shutdown, and handling task lifecycles
ScheduledExecutorServiceRepeating background work at fixed intervals

An executor is not automatically daemon-based. Its threads are usually user threads unless you provide a custom ThreadFactory.

Take Quiz

Cheat Sheet

Thread thread = new Thread(() -> {
    // background task
});

thread.setDaemon(true); // Call before start()
thread.start();
  • new Thread(...) creates a user thread by default.
  • thread.isDaemon() checks whether a thread is a daemon.
  • Call setDaemon(true) before start().
  • Calling setDaemon(...) after start() throws IllegalThreadStateException.
  • The JVM exits when no user threads remain.
  • Daemon threads can be stopped when the JVM exits.
  • Do not use daemon threads for critical writes, transactions, or required cleanup.
  • Child threads generally inherit the daemon status of the thread that creates them.
  • Prefer executors for managed application background tasks.

FAQ

What is a daemon thread in Java?

A daemon thread is a background thread that does not keep the JVM alive. When all user threads finish, the JVM may stop daemon threads and exit.

Are Java threads daemon threads by default?

No. Threads created with new Thread(...) are user threads by default. They normally inherit the daemon status of the thread that creates them.

How do I make a thread a daemon thread in Java?

Call setDaemon(true) before calling start().

thread.setDaemon(true);
thread.start();

What happens if I call setDaemon(true) after start()?

Java throws IllegalThreadStateException because a thread's daemon status cannot change after it has started.

Does the JVM wait for daemon threads to finish?

No. Once no user threads remain, the JVM can exit without waiting for daemon threads to finish.

Can a daemon thread run forever?

Its code can contain an infinite loop, but it only runs while the JVM remains alive due to user threads or other conditions. It can end abruptly at JVM shutdown.

Should I use a daemon thread for file saving?

No. File saving is important work that should finish reliably. Use a user thread or a managed executor and wait for completion during shutdown.

Is the garbage collector a daemon thread?

Garbage collection is an example of JVM background activity commonly associated with daemon behavior. Application code should not rely on its exact thread implementation or timing.

Take Quiz

Mini Project

Description

Build a small application that simulates a program doing foreground work while a daemon thread prints periodic status updates. It demonstrates that the background status reporter does not keep the JVM alive after the foreground work finishes.

Goal

Create a daemon status reporter that runs while the main thread performs three pieces of work, then observe the program exit when main ends.

Requirements

Create a thread that prints a status message every 500 milliseconds. Mark the status thread as a daemon before starting it. Make the main thread perform three timed work steps. Print a final message when the main work is complete. Handle InterruptedException correctly in both thread tasks.

Take Quiz

Keep learning

Related questions

View more