Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Daemon Thread

The low priority thread that executes in the background is known as the daemon thread.

Examples of daemon threads

        i)   Garbage Collector
        ii)   finalizer
        iii)  Attach Listener, etc.

For example, JVM executes Garbage Collector in the background to destroy the objects without reference. It is unknown to the programmer that when the garbage collector will be executed by JVM.

When all the non-daemon threads die, automatically all the daemon threads will be terminated by JVM.

It is possible to check whether any thread is daemon or not by using isDaemon() method.

Syntax of isDaemon() method

public boolean isDaemon()

We can set any thread as a daemon thread by using setDaemon() method.

Syntax of setDaemon() method

public void setDaemon(boolean flag)

Example

 class UserThread extends Thread
 {
     public static void main(String args[])
     {
         UserThread t1 = new UserThread();
         UserThread t2 = new UserThread();
         t2.setDaemon(true);
         System.out.println("Is t1 Daemon :: "+t1.isDaemon());
         System.out.println("Is t2 Daemon :: "+t2.isDaemon());
     }
 }

Output

Is t1 Daemon :: false
Is t2 Daemon :: true

Once any thread is started, it cannot be converted into daemon thread. Otherwise, it will throw IllegalThreadStateException.

Example

 class UserThread extends Thread
 {
     public void run()
     {
         System.out.println("Thread Started");
     }
 }

 class Demo
 {
     public static void main(String args[])
     {
         UserThread t = new UserThread();
         t.start();
         t.setDaemon(true);
         System.out.println("Is User thread t Daemon :: "+t.isDaemon());
     }
 }

Output

Thread Started
Exception in thread "main" java.lang.IllegalThreadStateException

 

Leave a reply