InterviewSolution
| 1. |
Daemon Threads in Java |
|
Answer» Daemon Thread are a specific kind of thread in JAVA that has the lowest priority while multithreading. All the User Threads have higher priority than the Daemon Thread. It cannot STOP the JVM from exiting while rest of the threads have finished executing. JVM doesn’t depend on the execution of the daemon threads. The Daemon thread performs background TASKS like Garbage collection but is terminated as soon as the User Threads complete their execution. JVM doesn’t take into consideration whether the Daemon Thread is STILL running or not. It terminates the threads and then shuts itself down. Daemon thread in java is a service provider thread that provides services to the user thread. There are many automatic daemon threads like gc and finalizer. Methods for the Daemon thread include: public void setDaemon(boolean status)The void setDaemon(boolean status) labels the current thread as a Daemon thread or an User Thread public boolean isDaemon()The boolean isDaemon() checks whether the thread is a Daemon thread or not. Let us see the execution of Daemon Threads along with User Threads public class Example extends Thread { public Example(String thread_name) { super(thread_name); } public void run() { if(Thread.currentThread().isDaemon()) { System.out.println(getName() + " is just a Daemon thread "); } else { System.out.println(getName() + " is an User thread!!!!"); } } public static void main(String[] args) { Example t1 = new Example("t1"); Example t2 = new Example("t2"); Example t3 = new Example("t3"); Example t4 = new Example("t4"); t1.setDaemon(true); // making t1 as Daemon t1.start(); t2.setDaemon(true); // making t2 as Daemon t2.start(); t3.start(); // t3 is a user thread t4.setDaemon(true); // making t4 as Daemon } }The OUTPUT is as follows: $javac Example.java $java Example t1 is just a Daemon thread t2 is just a Daemon thread t3 is an User thread!!!!We can notice that after the execution of the User Thread t3 has completed, the Daemon Thread t4 terminates and is not checked for being a Daemon Thread. |
|