Thursday 27 August 2015

Daemon Thread


What is Daemon Threads ?

Daemon threads are those threads which perform some helper functions or provide services to non-daemon threads(user threads).When JVM starts up,it creates garbage collector thread or some housekeeping threads except main thread .this threads are called Daemon threads

Daemon threads runs in background to provide services to user threads.Daemon threads are low priority threads.When no user thread is running JVM terminates all the daemon threads .

Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class TestDaemonThreads extends Thread {  
      public static void main(String[] args) {  
           TestDaemonThreads daemonThread = new TestDaemonThreads();  
           TestDaemonThreads normalThread = new TestDaemonThreads();  
           daemonThread.setDaemon(true);  
           daemonThread.start();  
           normalThread.start();  
      }  
      public void run() {  
           if (Thread.currentThread().isDaemon()) {  
                System.out.println("Daemon Thread");  
           } else {  
                System.out.println("Normal Thread");  
           }  
      }  
 }  



 Output:-  
 Daemon Thread  
 Normal Thread  

Use of Daemon Threads:-

Daemon threads performs housekeeping tasks such as removing unwanted entries from memory cache,releasing memory of unused objects etc.

Enjoy Learning.


No comments:

Post a Comment