👻 What Is a Daemon Thread?
A daemon thread is a background thread that does not prevent the JVM from exiting.
In simpler terms:
- If only daemon threads are running, the JVM will shut down automatically.
- They’re considered non-essential to the program’s main logic.
🧪 Real-Life Analogy
Think of daemon threads like assistants:
- They do background tasks (like garbage collection, monitoring, etc.)
- But when the main work (non-daemon threads) is done, the JVM says: “Okay, assistants, we’re closing shop — time to go!”
And it shuts down, killing the daemon threads.
🧰 How to Make a Thread Daemon
Thread t = new Thread(() -> {
while (true) {
System.out.println("Background work...");
}
});
t.setDaemon(true); // must be called BEFORE start()
t.start();
❗ If you forget to call setDaemon(true)
before start()
, you’ll get an IllegalThreadStateException
.
⚠️ JVM Behavior
- If at least one non-daemon thread is running → JVM stays alive.
- If only daemon threads are running → JVM exits without waiting for them to finish.
✅ When to Use Daemon Threads
Use Case | Example |
---|---|
Background tasks | Logging, Metrics, Auto-saving |
System-level support | JVM garbage collector threads |
Non-critical monitoring | Heartbeat pings, cleanup tasks |
❌ When NOT to Use Daemon Threads
- For anything critical: file writes, user operations, database updates.
- Because daemon threads can be terminated abruptly when the JVM exits.
📌 Quick Demo
public class DaemonDemo {
public static void main(String[] args) {
Thread daemon = new Thread(() -> {
while (true) {
System.out.println("I'm a daemon thread.");
try { Thread.sleep(1000); } catch (InterruptedException e) {}
}
});
daemon.setDaemon(true);
daemon.start();
System.out.println("Main thread sleeping 2 seconds...");
try { Thread.sleep(2000); } catch (InterruptedException e) {}
System.out.println("Main thread done.");
// JVM exits here — daemon thread is killed
}
}
🧨 Output will stop after main thread finishes — even if daemon is still looping.
🧠 Summary
Feature | Description |
---|---|
Daemon thread | Background thread — doesn’t block JVM exit |
Set with | thread.setDaemon(true) |
Use for | Monitoring, housekeeping |
JVM kills it when | No non-daemon threads are running |