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
mainthread 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.
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 (() -> {
() {
System.out.println();
{
Thread.sleep();
} (InterruptedException exception) {
Thread.currentThread().interrupt();
;
}
}
});
statusReporter.setDaemon();
statusReporter.start();
Thread.sleep();
System.out.println();
}
}
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:
- The JVM starts the user thread named
main. maincreateshelper, but it is not running yet.- marks as a daemon thread.
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.
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();
}
}
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
Comparisons
| Feature | User thread | Daemon thread |
|---|---|---|
Default for new Thread(...) | Yes | No |
| Keeps the JVM alive | Yes | No |
| Suitable for essential work | Yes | No |
| May be abandoned when JVM exits | No, the JVM waits for it | Yes |
| Example use | Processing an API request | Optional cache cleanup |
Daemon thread vs executor service
| Choice | Best for |
|---|---|
Thread with setDaemon(true) |
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)beforestart(). - Calling
setDaemon(...)afterstart()throwsIllegalThreadStateException. - 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.
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.
Keep learning
Related questions
Add External JAR Files to an IntelliJ IDEA Java Project
Learn how to add external JAR dependencies to an IntelliJ IDEA Java project using module libraries, and when to use Maven or Gradle instead.
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Call a Method After a Delay in Android Java
Learn how to run Java code after a delay in Android using Handler.postDelayed, manage the main thread, and cancel callbacks safely.