Skip to content
On this page

Daemon Threads

The entry point of a Java program is the main thread, which can start other threads. When all threads have finished executing, the JVM exits, and the process ends. If any thread is still running, the JVM process will not terminate, so it’s essential to ensure all threads can finish promptly.

However, some threads are designed to run indefinitely, such as a timer thread that triggers tasks at regular intervals:

java
class TimerThread extends Thread {
    @Override
    public void run() {
        while (true) {
            System.out.println(LocalTime.now());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                break;
            }
        }
    }
}

If this thread does not terminate, the JVM process cannot exit. The question arises: who is responsible for ending this thread?

Often, these threads do not have an assigned handler to stop them. However, when other threads finish, the JVM process must also end. The solution is to use daemon threads.

Daemon threads are threads that serve other threads. In the JVM, when all non-daemon threads have completed, the virtual machine will exit regardless of whether any daemon threads are still running. Therefore, there is no need to worry about whether daemon threads have ended when the JVM exits.

Creating Daemon Threads

Creating a daemon thread is similar to creating a regular thread; the only difference is that you call setDaemon(true) before invoking start() to mark the thread as a daemon:

java
Thread t = new MyThread();
t.setDaemon(true);
t.start();

When writing code in daemon threads, it’s important to note that they should not hold any resources that require closing, such as open files. This is because when the JVM exits, daemon threads have no opportunity to close these resources, potentially leading to data loss.

Exercise

Use a daemon thread for your tasks.

Summary

  • Daemon threads are designed to serve other threads.
  • The JVM exits when all non-daemon threads have completed, terminating daemon threads as well.
  • Daemon threads should not hold resources that need to be closed (e.g., open files).
Daemon Threads has loaded