A 'daemon' thread in Java is a low-priority thread that runs in the background. It provides services to user threads so they can perform their tasks.
These are often used to perform background tasks like garbage collection, freeing up memory, and other housekeeping tasks. The main characteristic of a daemon thread is that it does not prevent the JVM (Java Virtual Machine) from exiting when all the user threads (main thread and its child threads) finish their execution.
For example, in a running Java application, besides the main thread executing the main()
method, there are several other daemon threads like the garbage collector running concurrently in the background.
Here's a basic implementation of a daemon thread:
public class ExampleDaemon extends Thread {
public void run() {
if(Thread.currentThread().isDaemon()) {
System.out.println("Daemon thread executing");
}
else {
System.out.println("User(normal) thread executing");
}
}
public static void main(String[] args) {
ExampleDaemon t1 = new ExampleDaemon(); //Creating thread
ExampleDaemon t2 = new ExampleDaemon();
ExampleDaemon t3 = new ExampleDaemon();
t1.setDaemon(true); //Setting t1 as daemon thread
t1.start();
t2.start();
t3.start();
}
}
In this code, t1
is set as a daemon thread. The rest are user threads that will prevent the JVM from exiting until their tasks are complete.
It's important to note that a thread must be set as a daemon before it's started, otherwise it throws IllegalThreadStateException
. Daemon threads should be used sparingly and with caution, as they can often result in unexpected results or unpredictable behavior if not carefully managed.
So to recap, daemon threads in Java are not high-priority threads, cannot be killed (only interrupted), and they aren't the main thread of an application, but low-priority threads that run in the background, aiding user threads in executing their tasks smoothly.