Daemon Thread

Daemon thread in Java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

Features of Daemon thread

  • It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.

  • Its life depends on user threads.

  • It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread?

  • The sole purpose of the daemon thread is that it provides services to user thread for background supporting task.

  • If there is no user thread, why should JVM keep running this thread.

  • That is why JVM terminates the daemon thread if there is no user thread.

Methods

MethodDescription
public void setDaemon(boolean status)is used to mark the current thread as daemon thread or user thread.
public boolean isDaemon()is used to check that current is daemon.

Examples

class TestDaemonThread1 extends Thread {
    public static void main(String[] args) {
        TestDaemonThread1 t1 = new TestDaemonThread1();//creating thread
        TestDaemonThread1 t2 = new TestDaemonThread1();
        TestDaemonThread1 t3 = new TestDaemonThread1();

        // now t1 is daemon thread
        t1.setDaemon(true);

        // starting threads
        t1.start();
        t2.start();
        t3.start();
    }

    public void run() {
        if (Thread.currentThread().isDaemon()) {//checking for daemon thread
            System.out.println("daemon thread work");
        } else {
            System.out.println("user thread work");
        }
    }
}  

Output

daemon thread work
user thread work
user thread work
class TestDaemonThread2 extends Thread {
    public static void main(String[] args) {
        TestDaemonThread2 t1 = new TestDaemonThread2();
        TestDaemonThread2 t2 = new TestDaemonThread2();
        t1.start();

        // will throw exception here
        t1.setDaemon(true);
        t2.start();
    }

    public void run() {
        System.out.println("Name: " + Thread.currentThread().getName());
        System.out.println("Daemon: " + Thread.currentThread().isDaemon());
    }
}  

Output:

Exception in thread "main" java.lang.IllegalThreadStateException
	at java.base/java.lang.Thread.setDaemon(Thread.java:1411)
	at TestDaemonThread2.main(scratch_12.java:6)
Name: Thread-0
Daemon: false


Process finished with exit code 1
``

<!--inArticleSlot-->
core java programming multithreading concurrency

Subscribe For More Content