JVM.Threads.What is the difference between a daemon thread and a user thread in JVM?

Daemon Thread vs. User Thread in JVM

In Java, threads are classified into two types:

  1. User Threads (non-daemon)
  2. Daemon Threads

Both types of threads execute in parallel, but the key difference is how they affect JVM termination.


1. User Threads

  • Definition: Regular threads that execute application logic.
  • JVM Behavior: JVM keeps running as long as there is at least one active user thread.
  • Use Cases:
    • Handling requests (e.g., web server threads).
    • Background processing tasks like calculations.
    • Main application logic.

Example:

public class UserThreadExample {
    public static void main(String[] args) {
        Thread userThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("User thread running...");
                try { Thread.sleep(1000); } catch (InterruptedException e) {}
            }
        });

        userThread.start();
        System.out.println("Main method finished.");
    }
}

✅ JVM waits for the user thread to finish before terminating.


2. Daemon Threads

  • Definition: Background service threads that run as long as there are user threads.
  • JVM Behavior: If only daemon threads remain, the JVM terminates automatically.
  • Use Cases:
    • Garbage Collector (GC).
    • Logging services.
    • Background tasks (e.g., monitoring).

Example:





public class DaemonThreadExample {
    public static void main(String[] args) {
        Thread daemonThread = new Thread(() -> {
            while (true) {
                System.out.println("Daemon thread running...");
                try { Thread.sleep(1000); } catch (InterruptedException e) {}
            }
        });

        daemonThread.setDaemon(true); // Setting it as daemon
        daemonThread.start();

        System.out.println("Main method finished.");
    }
}

JVM exits immediately after main finishes, stopping the daemon thread.


Key Differences

FeatureUser ThreadDaemon Thread
JVM ShutdownJVM waits for themJVM does NOT wait for them
Use CasesApplication logic (e.g., web server)Background tasks (e.g., GC, logging)
Created ByDefault (unless set otherwise)Must be explicitly set using setDaemon(true)
Behavior on ExitRuns until completionStops abruptly when JVM exits
ExamplesRequest handlers, computationsGC, monitoring services

3. Converting a User Thread to a Daemon Thread

You can convert a user thread into a daemon thread before starting it:

Thread thread = new Thread(() -> System.out.println("Daemon thread example"));
thread.setDaemon(true);  // Must be set BEFORE start()
thread.start();

❌ Calling setDaemon(true) after start() will throw IllegalThreadStateException.


When to Use Daemon Threads?

✅ Use daemon threads when:

  • You don’t need the thread to finish if the main application ends.
  • The thread is not performing critical tasks (e.g., caching, logging, GC). ❌ Avoid daemon threads for:
  • Tasks that must complete (e.g., writing files, transactions).

Would you like a deeper dive into real-world scenarios or multithreading optimizations? 🚀

This entry was posted in Без рубрики. Bookmark the permalink.