Wednesday, August 9, 2017

daemon thread

@reference_1_stackoverflow
What is Daemon thread in Java?

Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt. The jconsole tool provides information about 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 user threads.
  • Its life depends on user threads.
  • It is a low priority thread.
No.MethodDescription
1)public void setDaemon(boolean status)is used to mark the current thread as daemon thread or user thread.
2)public boolean isDaemon()is used to check that current is daemon.

Note: If you want to make a user thread as Daemon, it must not be started otherwise it will throw IllegalThreadStateException.


class TestDaemonThread2 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){
TestDaemonThread2 t1=new TestDaemonThread2();
TestDaemonThread2 t2=new TestDaemonThread2();
t1.start();
t1.setDaemon(true);//will throw exception here
t2.start();
}
}
@reference_2_javatpoint.com
Daemon Thread in Java

No comments:

Post a Comment