JAVA

daemon thread

neal89 2025. 3. 7. 09:09

1️⃣ What is a Daemon Thread?

  • A background thread that performs auxiliary tasks.
  • JVM automatically terminates all daemon threads once all non-daemon threads finish.
  • Example: Garbage Collector (GC), logging, automatic backup.

2️⃣ What is a Non-Daemon Thread?

  • A regular thread that handles main application tasks.
  • JVM keeps running until all non-daemon threads are finished.
  • Example: Handling user requests, running main applications.

3️⃣ Comparison Table

Feature Daemon Thread Non-Daemon Thread

Purpose Background tasks Main application tasks
JVM Termination Stops when all non-daemon threads exit JVM waits until it finishes
Examples GC, logging, monitoring User input handling, main application

4️⃣ Code Example for Comparison

class MyDaemonThread extends Thread {
    public void run() {
        while (true) { // Infinite loop (daemon thread)
            System.out.println("Daemon thread running...");
            try { Thread.sleep(1000); } catch (InterruptedException e) {}
        }
    }
}

class MyNonDaemonThread extends Thread {
    public void run() {
        System.out.println("Non-Daemon thread started.");
        try { Thread.sleep(3000); } catch (InterruptedException e) {}
        System.out.println("Non-Daemon thread finished.");
    }
}

public class Main {
    public static void main(String[] args) {
        MyDaemonThread daemonThread = new MyDaemonThread();
        daemonThread.setDaemon(true); // ✅ Set as daemon thread
        daemonThread.start();

        MyNonDaemonThread nonDaemonThread = new MyNonDaemonThread();
        nonDaemonThread.start(); // Start non-daemon thread

        try { Thread.sleep(4000); } catch (InterruptedException e) {}
        System.out.println("Main thread exiting...");
    }
}

🛠 Expected Output

Daemon thread running...
Non-Daemon thread started.
Daemon thread running...
Daemon thread running...
Non-Daemon thread finished.
Main thread exiting...

nonDaemonThread runs until completion.
When the main thread exits, daemonThread also stops automatically.


5️⃣ How to Set a Daemon Thread in Java

📌 Daemon thread must be set before calling start(). Otherwise, it throws IllegalThreadStateException.

✅ Ways to Set a Daemon Thread

  1. Set inside the constructor of a Thread subclass
    class MyThread extends Thread {
        public MyThread() {
            setDaemon(true); // ✅ Set daemon in constructor
        }
    
        public void run() {
            System.out.println("Running as daemon: " + isDaemon());
        }
    }
    
  2. Set before calling start() in main()
    MyThread t1 = new MyThread();
    t1.setDaemon(true); // ✅ Set daemon before starting
    t1.start();
    
  3. Use an anonymous thread
    Thread t = new Thread(() -> System.out.println("Daemon running"));
    t.setDaemon(true); // ✅ Must set before start()
    t.start();
    

6️⃣ Conclusion

📌 Daemon ThreadRuns in the background, stops when all non-daemon threads exit.
📌 Non-Daemon ThreadMain application tasks, JVM waits for its completion.
📌 To create a daemon thread, use setDaemon(true) before calling start().

📌 In run method, you can't setDeamon().