Daemon Threads

This section describe about daemon thread in java. Any thread can be a daemon thread.

Daemon Threads

This section describe about daemon thread in java. Any thread can be a daemon thread. Daemon thread are service provider for other thread running in same process, these threads are created by JVM for background task. Any thread created by main thread that run the main method is by default user thread because it inherit the daemon nature from its parent thread from which it is created. Any thread which is created by user thread is user or non daemon thread only, until setDaemon(true) method is true. Thread.setDaemon(true) will create a daemon thread but it can be called only before thread is started or it will throw IllegalThreadStateException if thread is already started and running. The java.lang.Thread class provide two method for daemon thread as follows :

  • public void setDaemon(boolean value) - used to make the user thread as daemon thread.
  • public boolean isDaemon() -  To check whether the thread is daemon thread or not.

Main purpose of daemon thread is to provide services for background task of  user thread if there is not any user thread then JVM will terminate the daemon thread.

Example : A code for creating Daemon Thread

public class DaemonThread  extends Thread
  public void run()
   public static void main(String args[])
	   DaemonThread ob1=new DaemonThread ();
	   DaemonThread ob2=new DaemonThread ();
       //ob2.setDaemon(true);// Not allowed it will throw an exception.

If a user thread is set true to setDaemon() method for creating daemon thread, then it will only allow before thread is started or else it will result an error.

Output : After compiling and executing the above program

Download SourceCode

Share on Google+Share on Google+

Daemon Threads

Posted on: May 22, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Daemon Threads  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image