Fundamentals 4 min read

Understanding Java Daemon Threads and How to Create Them

This article explains what daemon threads are in Java, how they differ from user threads, the importance of setDaemon(true), provides the official setDaemon method documentation, and includes a complete demo program showing a daemon thread printing messages every second until the main thread ends.

FunTester
FunTester
FunTester
Understanding Java Daemon Threads and How to Create Them

In Java, the runtime uses a special type of thread called a daemon thread to perform background tasks such as garbage collection; if the only threads running in the JVM are daemon threads, the JVM will exit.

When using daemon threads, be aware that their tasks may be terminated abruptly when the runtime shuts down.

Creating a daemon thread is as simple as calling the setDaemon() method with true ; passing false marks the thread as a user thread. By default, all threads are created with daemon status false .

/**
 * Marks this thread as either a daemon thread or a user thread.
 * The Java Virtual Machine exits when the only threads running are all daemon threads.
 *
 * @param on if true, marks this thread as a daemon thread
 * @throws IllegalThreadStateException if this thread is alive
 * @throws SecurityException if the current thread cannot modify this thread
 */
public final void setDaemon(boolean on) {
    checkAccess();
    if (isAlive()) {
        throw new IllegalThreadStateException();
    }
    daemon = on;
}

The demo creates a daemon thread that logs a message every second. The main thread sleeps for five seconds, then ends; because the only remaining thread is the daemon thread, the JVM terminates and the daemon thread stops.

import org.slf4j.Logger;

class TSSS extends FanLibrary {
    public static Logger logger = getLogger(TSSS.class);

    public static void main(String[] args) {
        Thread daemonThread = new Thread(new Runnable() {
            public void run() {
                while (true) {
                    logger.info("Daemon thread is running!" + TAB + Time.getDate());
                    sleep(1000);
                }
            }
        });
        daemonThread.setDaemon(true);
        daemonThread.start();
        sleep(5000);
        logger.info("Main thread ends!");
    }
}

Sample console output shows the daemon thread logging timestamps each second, followed by the main thread termination message, and the process exits with code 0.

JavaConcurrencyThread ManagementDaemon ThreadsetDaemon
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.