Daemon threads & Non daemon Threads

The strict difference is that a daemon thread is one which won’t prevent the program from ending. This may not be a very useful way to describe the difference, though, so here’s an example:
Imagine a Java application. It starts off with just one thread, the “main” thread which runs the main method. This is a regular (non-daemon) thread. Now imagine again that the program starts another thread which sits in a loop doing something. If the new thread is a regular (non-daemon) thread, it will prevent the program from finishing when “main” ends, and keep going forever!

// print "hello" every second
class HelloThread extends Thread
{
  public void run()
  {
    for ( ; ; )
    {
      System.out.println("hello");
      sleep(1000);
    }
  }
}
public class RegularThreader
{
  public static void main(String[] args)
  {
    Thread hello = new HelloThread();
    hello.start();
    System.out.println("Sorry, I must be leaving");
  }
}

Now, this isn’t always what is required. Sometimes you want to end this “background” processing when the program finishes. To do this, you can mark threads as daemon threads. Daemon threads don’t prevent the program from ending, but stop when the main thread, stops:

public class DaemonThreader
{
  public static void main(String[] args)
  {
    Thread hello = new HelloThread();
    hello.setDaemon(true);
    hello.start();
    System.out.println("Sorry, I must be leaving");
  }
}

Try running the two different classes above, and see how the
output is different.
A classic example of a daemon thread is the garbage collector thread found in many Java Virtual Machines. It needs to run continuously while any other threads are running, but should not prevent the program from exiting. When the program exits, there is no more need for a garbage collector.

Advertisements
This entry was posted in Core JAVA, Just 4 Knowledge. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s