Sobes.tech
Junior

What is a daemon thread in Java?

sobes.tech AI

Answer from AI

Daemon Thread in Java is a background thread that does not prevent the JVM from exiting. The JVM terminates when all non-daemon threads have finished. If only daemon threads remain, the JVM also exits.

Main characteristics:

  • Background execution: Designed for running tasks in the background, such as garbage collection, monitoring, or service operations.
  • Does not prevent JVM termination: Their existence does not keep the JVM alive.
  • Parent determines status: The status of a new thread (daemon or not) is inherited by default from the thread that created it.
  • Explicit setting: You can explicitly set a thread as a daemon using the setDaemon(true) method before it starts. Changing the status after starting will throw an IllegalThreadStateException.

Example of creation and usage:

// Example Daemon Thread
Thread daemonThread = new Thread(() -> {
    while (true) {
        try {
            Thread.sleep(1000);
            System.out.println("Daemon thread is running...");
        } catch (InterruptedException e) {
            System.out.println("Daemon thread interrupted.");
            break;
        }
    }
});
daemonThread.setDaemon(true); // Setting Daemon status
daemonThread.start();

// Main thread
System.out.println("Main thread has started.");
try {
    Thread.sleep(3000); // Main thread runs for 3 seconds
} catch (InterruptedException e) {
    e.printStackTrace();
}
System.out.println("Main thread is ending.");
// After the main thread ends, the JVM will shut down,
// even if the daemon thread is still running

Comparison with user threads:

Characteristic Daemon Thread User Thread
Purpose Background tasks, services Main application logic, user operations
JVM termination Does not prevent JVM from exiting Prevents JVM from exiting
Lifecycle Ends with JVM Ends only after completing its tasks
Inheritance of status Inherits from parent thread Inherits from parent thread
Setting status Explicitly set with setDaemon(true) before start() Defaults to setDaemon(false)

It is important to use daemon threads with caution, as they can be unexpectedly terminated by the JVM. For tasks requiring guaranteed completion (e.g., saving data), user threads should be used.