Daemon Thread vs User Thread in Java

1. Introduction

In Java, threads can be categorized into two types: daemon threads and user (non-daemon) threads. A daemon thread is a low-priority thread that runs in the background to perform tasks such as garbage collection or to handle background tasks like waiting for input. A user thread, on the other hand, is a high-priority thread that is used to execute application code.

2. Key Points

1. Daemon threads are used to perform background supporting tasks and are only needed while normal threads are executing.

2. User threads are designed to execute application-level work and the JVM will wait for any user thread to complete before terminating.

3. Daemon threads do not prevent the JVM from exiting once all user threads have finished executing.

4. User threads can be thought of as the application's main workers, whereas daemon threads are like service providers to user threads.

3. Differences

Daemon Thread User Thread
Does not prevent the JVM from exiting when the program finishes. The JVM will wait for the user thread to complete before it terminates.
Generally used for asynchronous tasks like garbage collection, session management etc. Used for executing application logic in a concurrent manner.
Should be used sparingly, only for tasks that should not block the JVM from shutting down. Commonly used throughout applications whenever concurrent execution is needed.

4. Example


public class ThreadExample {

    public static void main(String[] args) {
        Thread userThread = new Thread(() -> {
            // This is a user thread that the JVM will wait to finish before exiting
            System.out.println("User Thread running");
            try {
                Thread.sleep(1000); // User thread is sleeping
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("User Thread finished");
        });

        Thread daemonThread = new Thread(() -> {
            // This is a daemon thread that the JVM will NOT wait to finish before exiting
            System.out.println("Daemon Thread running");
            try {
                Thread.sleep(3000); // Daemon thread is sleeping
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Daemon Thread finished");
        });
        daemonThread.setDaemon(true); // Setting the thread as daemon

        userThread.start();
        daemonThread.start();
    }
}

Output:

User Thread running
Daemon Thread running
User Thread finished
// The JVM may terminate before the daemon thread outputs "Daemon Thread finished"

Explanation:

1. The daemonThread is set as a daemon thread using the setDaemon(true) method.

2. The userThread is a normal thread that will complete its run method before the JVM exits.

3. The JVM will wait for the userThread to complete, but not for the daemonThread if it's still running, hence it may terminate before the daemon thread has finished.

5. When to use?

- Use daemon threads for background tasks that should not block the JVM from shutting down, like monitoring tasks, clean-up tasks, or to provide services to user threads.

- Use user threads for the main operations of your application, as the JVM will ensure that all user threads have been completed before termination.

Comments