Daemon Thread

A daemon thread is simply a thread that serves other threads only. During execution, a daemon thread behaves just like a user thread. It is almost same as user thread. As daemon threads exist just to serve user threads, so if there are no more user threads then all daemon threads are terminated by the JVM automatically. Daemon threads are suitable for background tasks like garbage collection process. The garbage collection runs from time to time and get the memory free from those objects that no longer have valid references. That is why Java programmers does not need to worry about memory management. Hence garbage collector is useful thread, which is marked as a daemon thread.

Implementation:

The following program demonstrates how to create daemon threads and how daemon threads are dependent on user threads for their execution. In this program, main thread creates and starts a daemon thread. To mark the thread as a daemon thread, main calls setDaemon() method.

 // DaemonThread.java
class AlphabetService extends Thread
       {
        //this process will take min. 2600 milliseconds to complete
	public void run ()
	         {
		System.out.println(“Printing Started by Daemon thread”);
		      for(char ch=65;ch<=90;ch++)
			{
			     System.out.print(ch+"  ");
			     try{  sleep(100); }
			    catch(Exception ex){ex.printStackTrace();}
			}
		      System.out.println(“Printing Completed...”);	
		}
	}
public class DameonThread 
  {    public static void main(String[] args) 
	{
	       System.out.println(“Main thread ( non-daemon) started”);	
	       	AlphabetService serviceThread=new AlphabetService();
		serviceThread.setDaemon(true);
		serviceThread.start();
		try{  Thread.sleep(1000);}
		catch(Exception ex){}
	  System.out.println(“\nMain thread ( non-daemon) stopped”);	
	}
  }
  Output
Main thread ( non-daemon) started
Printing Started... by Daemon thread
A      B      C      D      E      F      G      H      I      J      
Main thread ( non-daemon) stopped

About the Author
Rajesh K. Bansal (SCJP-Sun Certified Java Programmer)
17 Years experience in Training & Development. Founder of realJavaOnline.com, loves coding in Java(J2SE, J2EE), C++,PHP, Python, AngularJS, Android. If you like tutorials and want to know more in depth about Java , buy his book "Real Java" available on amazon.in.
#Email : [email protected] #Contact : 98722-46056
Available on Amazon
Card image cap
Under the guidance of Founder & Author of "realJavaOnline.com". M:9872246056
Card image cap