java tutorial - Daemon Thread in Java - java programming - learn java - java basics - java for beginners



Daemon thread in java

Learn Java - Java tutorial - Daemon thread in java - Java examples - Java programs

  • The Daemon thread is a service provider thread which gives services to the client (user) thread.
  • Its life depend upon the mercy of client threads i.e. when all the user threads dies, JVM terminates this thread mechanically.
  • There are many java daemon threads running automatically e.g. gc, finalizer etc.
  • We can also see each and every detail by typing jconsole in the command prompt.
  • The jconsole tool provides information concerning the loaded classes, memory usage, running threads etc.

Points to remember for Daemon Thread in Java

  • It provides services to user threads for background supporting tasks. It has no role in life than to serve client threads.
  • Its life depends on user threads.
  • It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread?

  • The sole purpose of the daemon thread is that it provides services to user thread for background supporting task.
  • If there is no user thread, why should JVM keep running this thread? That is why JVM terminates the daemon thread if there is no user thread.

Methods for Java Daemon thread by Thread class

  • The java.lang.Thread class provides two methods for java daemon thread.

Sample Code

File: MyThread.java

public class DaemonThread extends Thread{
 public void run(){
  if(Thread.currentThread().isDaemon()){//checking for daemon thread
   System.out.println("daemon thread work");
  }
  else{
  System.out.println("user thread work");
 }
 }
 public static void main(String[] args){
  DaemonThread time1=new DaemonThread();//creating thread
  DaemonThread time2=new DaemonThread();
  DaemonThread time3=new DaemonThread();

  time1.setDaemon(true);//now time1 is daemon thread
  
  time1.start();//starting threads
  time2.start();
  time3.start();
 }
}
click below button to copy the code. By - java tutorial - team

Output

daemon thread work
user thread work
user thread work

File: MyThread.java

public class DaemonThread extends Thread{  
 public void run(){  
  System.out.println("Name: "+Thread.currentThread().getName());  
  System.out.println("Daemon: "+Thread.currentThread().isDaemon());  
 }  
  
 public static void main(String[] args){  
  DaemonThread time1=new DaemonThread();  
  DaemonThread time2=new DaemonThread();  
  time1.start();  
  time1.setDaemon(true);//will throw exception here  
  time2.start();  
 }  
}  
click below button to copy the code. By - java tutorial - team

Output

Name: Thread-0
Daemon: false
Exception in thread "main" java.lang.IllegalThreadStateException

Related Searches to Daemon Thread in Java