Tuesday, 12 July 2011

Java Daemon thread And User Thread

What is difference between User and Daemon Thread in Java?

Java makes a distinction between a user thread and another type of thread known as a daemon thread. The daemon threads are typically used to perform services for user threads. The main() method of the application thread is a user thread. Threads created by a user thread are user thread. JVM doesn't terminates unless all the user thread terminate.
You can explicitly specify a thread created by a user thread to be a daemon thread by calling setDaemon(true) on a Thread object. For example, the clock handler thread, the idle thread, the garbage collector thread, the screen updater thread, and the garbage collector thread are all daemon threads. A new created thread inherits the "daemon-status" of the thread that created it unless you explicitly calling setDaemon on that Thread object to change its status.
Note that the setDaemon() method must be called before the thread's start() method is invoked.Once a thread has started executing (i.e., its start() method has been called) its daemon status cannot be changed. To determine if a thread is a daemon thread, use the accessor method isDaemon().

The difference between these two types of threads is straightforward: If the Java runtime determines that the only threads running in an application are daemon threads (i.e., there are no user threads in existence) the Java runtime promptly closes down the application, effectively stopping all daemon threads dead in their tracks. In order for an application to continue running, it must always have at least one live user thread. In all other respects the Java runtime treats daemon threads and user threads in exactly the same manner.

Small Example With Daemon thread.

public class DaemonThread extends Thread {
  public void run() {
  System.out.println("Entering run method");

  try {
  System.out.println("In run Method: currentThread() is"
  + Thread.currentThread());

  while (true) {
  try {
  Thread.sleep(500);
  catch (InterruptedException x) {
  }

  System.out.println("In run method: woke up again");
  }
  finally {
  System.out.println("Leaving run Method");
  }
  }
  public static void main(String[] args) {
  System.out.println("Entering main Method");

  DaemonThread t = new DaemonThread();
  t.setDaemon(true);
  t.start();

  try {
  Thread.sleep(3000);
  catch (InterruptedException x) {
  }

  System.out.println("Leaving main method");
  }

}