Site icon JavaGoal

Daemon thread in java

In java, we have learned many things about the multithreading in recent posts. There are two types of threads, user thread and daemon thread.  We have already discussed the user thread in separate posts. In this post, we will learn what is daemon thread in java and what is the use of Java daemon thread.

Here is the table content of the article will we will cover this topic.
1. What is daemon thread in java?
2. Properties of daemon thread
3. Create a daemon thread?
4. Importance of Daemon thread

What is daemon thread in java?

Each thread has its priority and it can be a lower or higher priority. Unlike user threads, daemon thread has low priority and it always runs in the background.  Daemon thread is useful to run some background tasks like garbage collection. The JVM doesn’t consider daemon thread as an important thread and it terminates itself even daemon thread has finished or not.

It means when all the user threads finish their execution, the JVM terminates the program whether any daemon thread is present or not. We can make a used thread as a daemon thread by invoking thread.setDaemon(true). But it should be done only before the thread is started otherwise it will throw IllegalThreadStateException.

Properties of daemon thread

1. A daemon thread is a service provider thread that provides services to the user thread. It
works in the background and gives support to the user thread.
2. The life of daemon thread depends on the user threads. When all the user threads finish, JVM
terminates daemon thread automatically. If JVM has finished the execution of user thread, it
will not wait for daemon thread to finish the execution.
3. As we know a thread always inherit some properties of its parent thread. A daemon thread also
inherits the daemon status of its parent. As we have seen if we create any thread inside the main
thread(User thread or non-daemon thread) , then the created thread(child thread) also a user
thread by default. In manner when we create a new thread from daemon thread, it create a
daemon thread.
4. daemon threads are low priority threads.
5. As we know a thread always inherits some properties of its parent thread. A daemon thread
also inherits the daemon status of its parent. As we have seen if we create any thread inside the
main thread(User thread or non-daemon thread), then the created thread(child thread) also a
user thread by default. In manner when we create a new thread from daemon thread, it creates a daemon thread.  

Create a daemon thread?

A daemon thread is created like user thread. Infect there is no special way to create a daemon thread, we just need to call a method and we can convert a user thread to daemon thread.

The Thread class provides a setDaemon(boolean status) method that is used for making a user thread to Daemon thread or vice versa. To make a daemon thread we need to pass the status parameter with true.  
Let’s take an example how we can create daemon thread by use of setDaemon(boolean status).This method should be invoked before the thread is started otherwise it will throw IllegalThreadStateException.

public class MainClass 
{
    public static void main(String args[]) 
    {
    	MyThread myThread = new MyThread();   
    	myThread.setDaemon(true);
    	myThread.start();
        
    	// Sleep for five seconds
        try 
        {
            Thread.sleep(5000);
        } catch (InterruptedException ignored) {
        }
        System.out.println("Main thread finished");
    }
}
    
class MyThread extends Thread
{
    public void run() 
	{
		while (true) {
        System.out.println("Daemon thread is running");
        try {
               Thread.sleep(500);
             } 
        catch (InterruptedException ignored) {
                }
            }
    }
}

Output: Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Main thread finished

Importance of Daemon thread

The Daemon thread is always run in the background. The main purpose of the daemon thread is that it provides services to user threads. If some user thread needs support from the 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.

We can set a thread as a Daemon thread and check any thread is a daemon thread. Thread class provides two methods:

1. public final boolean isDaemon()
2. public final void setDaemon (boolean on)

1. public final boolean isDaemon(): This method returns a boolean value either true or false. This method is used to check whether the thread is daemon thread or not. It is a public and final method. Its return type is boolean.

2. public final void setDaemon (boolean on): This method is used to set a thread as daemon thread. You can mark any user thread as a daemon thread bypassing the value true (setDaemon(true)) in the parameter. If I have a Daemon thread and you can make it user thread bypassing the value false setDaemon(false)).  It is a public and final method. Its return type is void it means it doesn’t return anything.

public class ExampleOfDaemonThread extends Thread
{
   public void run()
   {  
     if(Thread.currentThread().isDaemon()) 
     { 
	 try 
	 { 
		 Thread.sleep(2000); 
	 }
	 catch (InterruptedException e) 
	 { 
		 e.printStackTrace(); 
	 } 
     }
     for(int i = 1; i <= 5; i++)
     {
  System.out.println(Thread.currentThread().getName() + " is running and value of i = " +i);
     }
   } 
   public static void main(String[] args)
   {  
		 ExampleOfDaemonThread thread1=new ExampleOfDaemonThread();
		 thread1.setName("Thread1");
		 ExampleOfDaemonThread thread2=new ExampleOfDaemonThread();  
		 thread2.setName("Thread2");
		 ExampleOfDaemonThread thread3=new ExampleOfDaemonThread();  
		 thread3.setName("Thread3");
		  
		 thread1.setDaemon(true);
		    
		 thread1.start();
		 thread2.start();  
		 thread3.start();  
   }  
}  

Output:
Thread3 is running and value of i = 1
Thread2 is running and value of i = 1
Thread3 is running and value of i = 2
Thread2 is running and value of i = 2
Thread3 is running and value of i = 3
Thread2 is running and value of i = 3
Thread3 is running and value of i = 4
Thread2 is running and value of i = 4
Thread3 is running and value of i = 5
Thread2 is running and value of i = 5

In the above example, we have three thread thread1, thread2, and thread3. We set the thread1 as a daemon thread. So now it is least important for the CPU. The thread2 and thread3 are the user threads. We called the start() method for each thread:

thread1.start();
thread2.start();
thread3.start();

After calling the start() method all threads move to the runnable state and waiting for the CPU cycle. Here, we want to sleep the daemon thread for 2 seconds, so we called the sleep() method for daemon thread. The CPU executed the thread2 and thread3. CPU terminates itself after the execution of user threads(thread1 and thread2). The CPU doesn’t wait for thread1 because the thread1 is daemon thread and CPU doesn’t care whether it is executed or not.

Exit mobile version