What is a daemon thread?

There are two types of threads: user threads and daemon threads. Typically, you create user threads. A Java application will not terminate unless all user threads have finished execution, including the one that executes main() (the main thread of execution). If a thread has the daemon flag set to true, the JVM will end it regardless of whether or not it still has more work to do, if there are no more other user threads running. A user thread keeps the application from terminating. A daemon thread doesn’t.

You specify a thread to be daemon by setting the daemon flag to be true, using the setDaemon method. This has to be done before the thread is started. The setDaemon method calls the method checkAccess from the System’s SecurityManager and will throw a SecurityException if you are not permitted to change the daemon status.

An example of a daemon thread is the JVM’s garbage collector thread.

The following two apps show the difference. The app WithoutDaemon will create a user thread that will print out 1000 numbers. WithDaemon creates a daemon thread instead and will only print out until the main execution thread reaches the end.

WithoutDaemon.java:

import java.net.*;

public class WithoutDaemon
{
   public static void main(String args[]) {
      Thread t = new WithoutDaemonThread();
      t.setDaemon(false);    // no need, default value!
      t.start();

      try {
         Thread.sleep(100);
      }
      catch(InterruptedException e) {
      }
   }
}

class WithoutDaemonThread extends Thread
{
   public void run() {
      for (int i=0; i<1000; i++)
         System.out.print(i + " ");
      System.out.println();
   }
}

WithDaemon.java:

import java.net.*;

public class WithDaemon
{
   public static void main(String args[]) {
      Thread t = new WithDaemonThread();
      t.setDaemon(true);
      t.start();

      try {
         Thread.sleep(100);
      }
      catch(InterruptedException e) {
      }
   }
}

class WithDaemonThread extends Thread
{
   public void run() {
      for (int i=0; i<1000; i++)
         System.out.print(i + " ");
      System.out.println();
   }
}