Daemon Thread vs User Thread in Java

 In Java multithreading, all threads are categorized into two types: User Threads and Daemon Threads. Understanding the difference between these two is crucial for writing efficient, reliable, and properly-managed concurrent applications.

While both user and daemon threads share a similar structure and behavior (they are both instances of the Thread class), they serve very different purposes.

In this article, we will explore the core differences between user threads and daemon threads, how the JVM handles them, and how to create and use them effectively.

What is a User Thread?

A User Thread is a foreground thread in Java that performs a specific task intended by the application. These are the threads that do the actual work — like processing user input, handling requests, reading or writing files, or performing calculations.

🔍 Key Characteristics:

  • JVM waits for all user threads to finish before exiting.
  • They are created by the application code.
  • Typically high-priority threads.
  • Run in the foreground and control the lifecycle of the JVM.
  • Used to perform core business logic or task execution.

Example of a User Thread:

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

userThread.start();
}
}

✅ Output:

User thread running: 1
User thread running: 2
User thread running: 3

In this case, the JVM waits for the user thread to complete before exiting the application.

What is a Daemon Thread?

A Daemon Thread is a background thread that provides support services to user threads. These are often created by the JVM to handle internal tasks like garbage collection, finalization, and other housekeeping duties.

🔍 Key Characteristics:

  • JVM does not wait for daemon threads to finish.
  • Runs in the background.
  • Automatically terminated when all user threads are finished.
  • Typically low-priority threads.
  • Used to support user threads, not perform application-level logic.

Example of a Daemon Thread:

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

daemonThread.setDaemon(true); // Set as daemon before starting
daemonThread.start();

try {
Thread.sleep(1500); // Main thread sleeps for a while
} catch (InterruptedException e) {
e.printStackTrace();
}

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

✅Output:

Daemon thread running in background...
Daemon thread running in background...
Daemon thread running in background...
Main thread finished

After the main (user) thread finishes, the JVM automatically terminates the daemon thread — even if it’s still running.

📊 Comparison Table: User Threads vs Daemon Threads

How to Create a Daemon Thread in Java?

You can make any thread a daemon thread by calling setDaemon(true) before starting it.

Thread t = new Thread(task);
t.setDaemon(true); // Must be called before start()
t.start();

If you try to set a thread as daemon after it has started, Java will throw:

IllegalThreadStateException

⚠️ Important Rules and Points to Remember

✅ 1. JVM Exit Behavior

  • JVM exits only after all user threads are done.
  • Daemon threads are terminated automatically when user threads are complete.

✅ 2. Don’t Use Daemon Threads for Critical Tasks

Since the JVM doesn’t wait for them, never run important logic (like saving files, writing logs) in daemon threads. You might lose data if the JVM exits while the daemon is still processing.

✅ 3. Can a User Thread Create a Daemon Thread?

Yes. Any thread can create another thread and mark it as a daemon:

Thread t = new Thread(task);
t.setDaemon(true);

✅ 4. Garbage Collector is a Daemon

The most well-known example of a daemon thread is the Garbage Collector (GC) thread, which reclaims memory in the background.

💡 Real-World Analogy

Let’s say you’re working late at an office:

  • You are a user thread, doing your work (the main task).
  • The janitor is a daemon thread, cleaning around and supporting your work.
  • If you leave the office (user thread exits), the janitor (daemon) will also stop — even if cleaning isn’t finished.

🛠️ Practical Use Case: Using Daemon Threads for Monitoring

Daemon threads are perfect for low-priority monitoring tasks, like:

  • Watching configuration files for changes
  • Logging background status
  • Sending heartbeat signals in the background
Thread monitor = new Thread(() -> {
while (true) {
System.out.println("Monitoring app status...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
break;
}
}
});
monitor.setDaemon(true);
monitor.start();

This thread keeps checking status in the background but won’t block the app from exiting.

✅ Final Thoughts

Understanding the difference between User Threads and Daemon Threads is fundamental for writing robust and scalable Java applications.

  • Use User Threads for core logic and essential operations.
  • Use Daemon Threads for non-critical background tasks that should not prevent the application from exiting.
  • Always remember that the JVM will not wait for daemon threads, so avoid putting essential tasks in them.

By using both types of threads wisely, you can make your Java applications more responsive, modular, and efficient.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare