Daemon Thread

Daemon thread in Java is used to provide services to the user threads for background supporting task (such as garbage collection). It is a low priority thread and its life depends on the user threads. If all user threads die, JVM terminates this thread automatically. Basically, when all user threads (i.e. non-daemon threads) finish, the JVM halts, and any remaining daemon threads are abandoned:

  • The finally blocks are not executed,
  • Stacks are not unwound – the JVM just exits.

Due to this reason daemon threads should be used carefully, and it is dangerous to use them for tasks that might perform any sort of I/O.

Methods:
  1. void setDaemon(boolean status): This method is used to mark the current thread as daemon thread or user thread.

           Syntax: public final void setDaemon(boolean on)

           parameters:

                   on: if true, marks this thread as a daemon thread.

           exceptions:

                   IllegalThreadStateException: if only this thread is active.

                  SecurityException: if the current thread cannot modify this thread.

  1. boolean isDaemon(): This method is used to check that current thread is daemon or not. It returns true if the thread is daemon else it returns false.

            Syntax: public final void setDaemon(boolean on)

            returns: This method returns true if this thread is a daemon thread; false otherwise.

The following program program demonstrates the usage of setDaemon() and isDaemon() method

DaemonThreadTesting.java

class CustomThread extends Thread {

    CustomThread(String name) {
        super(name);
    }

    public void run() {
        Thread t = Thread.currentThread();
        if (t.isDaemon()) {
            System.out.println(t.getName() + " is a daemon thread");
        } else {
            System.out.println(t.getName() + " is a user thread");
        }
   }
}

public class DaemonThreadTesting {

    public static void main(String[] args) {

        CustomThread t1 = new CustomThread("1st");
        t1.setDaemon(true);
        CustomThread t2 = new CustomThread("2nd");
        CustomThread t3 = new CustomThread("3rd");
        t1.start();
        //t1.setDaemon(true);
        t2.start();
        t3.start();
    }
}

Output:

1st is a daemon thread
3rd is a user thread
2nd is a user thread

See another coding example below.

DaemonThreadTesting.java

class WorkerThread extends Thread {
    boolean isDeamon;

    WorkerThread(boolean isDeamon) {
        // When false, (i.e. when it's a user thread),
        // the Worker thread continues to run.
        // When true, (i.e. when it's a daemon thread),
        // the Worker thread terminates when the main
        // thread terminates.
        this.isDeamon = isDeamon;
        setDaemon(isDeamon);
    }

    public void run() {
        System.out.println("I am a " + (isDeamon ? "Daemon Thread"
                                          : "User Thread (non-daemon)"));

      for (int count = 1; count <= 5; count++) {
            System.out.println("\tworking from Worker thread " + count);

            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {
                // handle exception here
           }
            finally {
                System.out.println("\tfinally executed "+ count);
            }
        }
        System.out.println("\tWorker thread ends. ");
    }

}

public class DaemonThreadTest {

   public static void main(String[] args) {

    new WorkerThread(false).start();//set it to true & false and run twice.
        try {
            Thread.sleep(2500);
       }
  catch (InterruptedException e) {
            // handle here exception
        }
        System.out.println("Main Thread ending");
    }
}

Output:

When set false
================
I am a User Thread (non-daemon)
            working from Worker thread 1
            finally executed 1
            working from Worker thread 2
            finally executed 2
            working from Worker thread 3
Main Thread ending
            finally executed 3
            working from Worker thread 4
            finally executed 4
            working from Worker thread 5
            finally executed 5
            Worker thread ends.

When set true
================
I am a Daemon Thread
            working from Worker thread 1
            finally executed 1
            working from Worker thread 2
            finally executed 2
            working from Worker thread 3
Main Thread ending