Java
Daemon Thread
Programming
Thread Management
Java Concepts

What is a daemon thread in Java?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Java programming, a thread is a lightweight process that allows a program to operate more efficiently by performing multiple tasks simultaneously. Threads can be categorized into two main types: user threads and daemon threads. The focus of this discussion is on the latter - daemon threads.

Definition of Daemon Thread

A daemon thread in Java is a type of thread that does not prevent the Java Virtual Machine (JVM) from exiting when the program finishes but the thread is still running. Daemon threads are typically used to perform services for user threads (non-daemon threads). The classic examples of daemon threads are garbage collector, finalizer thread, and timer thread.

Characteristics of Daemon Threads

Daemon threads are low-priority threads whose only role is to provide services to user threads. They have several distinct characteristics:

  • Background Execution: They run in the background and mostly perform tasks such as garbage collection, releasing memory of unused objects, etc.
  • Life Cycle: Their life cycle is bound to the lifespan of user threads. When all user threads die, the JVM terminates the daemon threads.
  • Doesn't prevent JVM termination: Unlike user threads, active daemon threads do not prevent the JVM from terminating. Once all user threads have finished executing, the JVM halts, regardless of whether daemon threads are still running.

Creating Daemon Threads in Java

Any thread can be a daemon thread in Java. The Thread class provides a method called setDaemon(boolean) that is used to mark a thread as a daemon thread or a user thread. To declare a thread as a daemon, you must call setDaemon(true) before the thread is started. Here is an example:

java
1// Creating a daemon thread in Java
2public class MyDaemonThread implements Runnable {
3    public void run() {
4        while (true) {
5            try {
6                // Perform some background operation
7                Thread.sleep(1000);
8                System.out.println("Running in the background.");
9            } catch (InterruptedException e) {
10                System.out.println("Interrupted");
11            }
12        }
13    }
14
15    public static void main(String[] args) {
16        Thread thread = new Thread(new MyDaemonThread());
17        thread.setDaemon(true); // Setting the thread as daemon
18        thread.start();
19
20        System.out.println("Main thread running and will finish");
21    }
22}

In the above example, the daemon thread will print a message every second. When the main method (and hence the main thread) complete execution, the JVM exits, halting the daemon thread, regardless of its state.

Use Cases and Considerations

Daemon threads are ideally suited for tasks that need to run in the background, such as periodic housekeeping activities. However, it is crucial to ensure that these tasks are not critical to the application's correctness since they may not complete if the JVM shuts down.

Summary Table

FeatureUser ThreadDaemon Thread
JVM ExitPreventsDoes not prevent
UsageMain application tasksBackground supporting tasks
ExampleBusiness logicGarbage collector, monitoring
LifespanAs long as the application runsEnds when user threads finish

Conclusion

Daemon threads serve a specific purpose in Java, acting mainly as housekeepers or service providers for user threads. They run quietly in the background, efficiently playing their roles without obstructing the main application's termination process. Proper understanding and use of daemon threads can leverage the performance of Java applications by keeping the runtime environment clean and responsive. However, one must use caution because daemon threads are not suited for tasks that are critical to the application's state or result.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.