Setting a Thread as Daemon
You'll learn how to convert a thread into a daemon thread using setDaemon(true) before starting it.
The Core Mechanic
In the previous lesson, you learned what daemon threads are—background service threads that don't prevent JVM shutdown. Now you'll learn how to create them. The secret is the setDaemon(boolean) method, which must be called before the thread starts.
Here's the critical rule: you can only change a thread's daemon status when it's in the NEW state. Once you call start(), the thread's daemon status is locked in forever.
Basic Usage
Thread backgroundWorker = new Thread(() -> {
while (true) {
System.out.println("Working...");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
break;
}
}
});
// Convert to daemon BEFORE starting
backgroundWorker.setDaemon(true);
backgroundWorker.start();
System.out.println("Main thread finishing...");
// JVM exits immediately, backgroundWorker is killed mid-loop
Without setDaemon(true), this infinite loop would prevent the JVM from ever exiting.
Timing Matters
Thread thread = new Thread(() -> { /* task */ });
thread.start();
thread.setDaemon(true); // IllegalThreadStateException!
This throws an exception because the thread has already left the NEW state.
Checking Daemon Status
You can verify a thread's daemon status with isDaemon():
System.out.println(backgroundWorker.isDaemon()); // true
Key Takeaway: Use setDaemon(true) before calling start() to convert a thread into a daemon thread that won't prevent JVM shutdown; attempting to change daemon status on an already-running thread throws IllegalThreadStateException.