A daemon thread in Java is a background thread that provides support to user threads during program execution. These threads run in the background and automatically terminate when all user threads finish execution. In this chapter, we will learn what daemon threads are, how to create them, and how they behave in Java programs.
In Java, multithreading allows multiple tasks to run at the same time. Among different types of threads, daemon threads are special threads that run in the background to support other threads.
A daemon thread is a low-priority background thread that provides services to user threads, such as garbage collection or monitoring tasks. These threads work silently and do not require direct interaction from the programmer during normal execution.
A thread can be marked as a daemon thread using the setDaemon(boolean) method, and its status can be checked using the isDaemon() method.
Daemon thread's life depends entirely on user threads. When all user threads finish execution, the JVM automatically stops all daemon threads. Because of this behavior, daemon threads are mainly used for background tasks that should not prevent the program from terminating.
The main purpose of a daemon thread is to support user threads by performing background tasks. When there are no user threads running, the daemon threads have no work to do. Therefore, the JVM automatically stops all daemon threads.
The java.lang.Thread class provides the following two methods for Java daemon thread.
| No. | Method | Description |
|---|---|---|
| 1) | public void setDaemon(boolean status) | It is used to mark the current thread as daemon thread or user thread. |
| 2) | public boolean isDaemon() | It is used to check that current is daemon. |
A thread must be marked as a daemon before it is started. Once a thread starts execution, its daemon status cannot be changed.
Here are the steps to create a daemon thread:
If the daemon status is set after calling start(), the JVM throws an IllegalThreadStateException.
The syntax to mark a thread as daemon thread is:
To check whether a thread is a daemon thread or a user thread, Java provides the isDaemon() method.
The syntax to check a daemon thread status is:
Practice these examples to understand the concept of daemon threads.
The following example demonstrates how to create a daemon thread and how Java differentiates between daemon threads and user threads.
Output:
daemon thread work user thread work user thread work
A thread must be marked as a daemon before calling the start() method. If setDaemon(true) is called after the thread has started, Java throws an IllegalThreadStateException.
Output:
exception in thread main: java.lang.IllegalThreadStateException
We request you to subscribe our newsletter for upcoming updates.