What is daemon thread in java

Daemon Threads in Java

In this tutorial, we will learn about Daemon Threads in Java. We will see what a daemon thread is, how to create a daemon thread, various methods present for daemon threads in Thread class, usecases where we can use daemon threads and finally some of the differences between daemon and non-daemon threads.

Daemon Threads are the low-priority threads that will execute in the background to provide support for the non-daemon threads (a thread that executes the main logic of the project is called a non-daemon or user thread). Daemon Threads in Java are also known as Service Provider Threads.

Let us consider a situation where the main thread is running with low memory; then what JVM will do, it will run the Garbage Collector (GC) to destroy the unreachable objects so that the memory will be freed up and with this free memory, the main thread can continue its execution. So here this GC is a daemon thread that provides the service of cleaning memory for the main thread so that the main thread can continue its execution without any interruption. Hence the main objective of daemon threads is to provide services to main/user threads.

Some examples of Daemon Threads are Garbage Collector, Signal Dispatcher, Attach Listener, Finalizer, etc.

Let us discuss some of the important properties of Daemon Threads:

  • The life cycle of daemon threads depends on user threads. It provides services to user threads for background supporting tasks.
  • They cannot prevent the JVM from exiting when all the user threads finish their execution.
  • When all the user threads terminate, JVM terminates Daemon threads automatically.
  • It is a thread with the lowest priority possible.
  • JVM won’t be concerned about whether the Daemon thread is active or not.
Читайте также:  При клике выпадает меню css

2. Methods for Daemon Thread

The following methods directly create or test a thread to be daemon thread.

  • void setDaemon(boolean status): To make a thread a daemon thread. We can change the nature of a thread by using this method.
  • boolean isDaemon(): Used to determine whether or not the current thread is a daemon. If the thread is Daemon, it returns true; otherwise false.

In the following example, we are creating two threads. We are marking a thread daemon and then testing both threads to be daemon or user threads.

public class Task extends Thread < String threadName; public Task(String name)< threadName = name; >public void run() < if(Thread.currentThread().isDaemon()) < System.out.println(threadName + " is Daemon Thread"); >else < System.out.println(threadName + " is User Thread"); >> public static void main(String[] args) < Task thread1 = new Task("thread1"); Task thread2 = new Task("thread2"); // Making thread1 as Daemon thread1.setDaemon(true); thread1.start(); thread2.start(); >>
thread1 is Daemon Thread thread2 is User Thread

We can change the daemon nature of a thread using setDaemon() , but changing the daemon nature is possible before starting a thread only. After starting a thread, if we are trying to change the daemon nature, we will get IllegalThreadStateException.

Task thread = new Task("user-thread"); thread.start(); thread.setDaemon(true); // java.lang.IllegalThreadStateException

By default, the main thread is always non-daemon, and for all the remaining threads, daemon nature inherits from parent to child i.e. if the parent thread is daemon then automatically child thread is also daemon and vice-versa.

Since the main thread is a non-daemon thread, any other thread created from it will remain non-daemon until explicitly made daemon by calling setDaemon(true) method.

It is not possible to change the daemon nature of the main thread because the main thread is already been started by JVM at the beginning. If we try to change the daemon nature of the main thread by using setDaemon() method, then it will raise IllegalThreadStateException.

4. Daemon Thread Termination

JVM terminates all the daemon threads irrespective of whether daemon threads are running or not whenever the last user thread terminates. The main purpose of a daemon thread is to provide services to the user thread for background-supporting tasks. If there is no user thread, why should JVM keep running this daemon thread? That is why JVM terminates the daemon thread if there is no user thread.

class Task extends Thread < public void run()< for(int i=0;i<10;i++)< System.out.println("Child Thread is executing"); try < Thread.sleep(2000); >catch(InterruptedException e) < //. >> > > class ThreadDemo < public static void main(String[] args)< Task thread = new Task(); thread.setDaemon(true); thread.start(); System.out.println("Main thread is terminating"); >>

Notice the output. When the main/user thread terminates, immediately the daemon thread i.e. child thread terminates as well, and it won’t complete. It’s for-loop 10 times and JVM terminates it in the middle itself.

Child Thread is executing main thread is terminating

5. When to Use Daemon Threads?

Daemon threads are useful for background-supporting tasks such as garbage collection, releasing the memory of unused objects and removing unwanted entries from the cache.

We can use Daemon Threads in usecases like:

  • Collecting statistics and performing the status monitoring tasks – Sending and receiving network heartbeats, supplying the services to monitoring tools, and so on.
  • Performing asynchronous I/O tasks – We can create a queue of I/O requests, and set up a group of daemon threads servicing these requests asynchronously.
  • Listening for incoming connections – daemon threads are very convenient in situations like this because they let us program a simple “forever” loop rather than creating a setup that pays attention to exit requests from the main thread.

6. Difference between Daemon Thread and User Thread

Lets now collect some of the differences between daemon and non-daemon threads:

  • Creation: JVM creates Daemon threads, whereas an application creates its own user threads.
  • Usage:Daemon threads provide service to the user threads and always run in the background, whereas user threads are used for foreground and I/O tasks of an application.
  • Priority:Daemon threads are low-priority threads, whereas user threads are of high priority.
  • JVM Behavior: JVM does not wait for daemon threads execution to complete, whereas JVM waits till the execution of the user thread is finished.
  • Life Cycle: The daemon threads’ lifecycle depends on user threads, whereas user threads have an independent lifecycle.
  • Termination: All the daemon threads are terminated once the last user thread has been terminated, irrespective of the daemon thread’s position at that time, whereas user threads are terminated after completing their corresponding jobs.

In this Java concurrency tutorial, we learned what daemon threads are and how we can utilize them in a few real applications. We have also learned the main methods in Thread class to work with daemon threads and some of the main differences between daemon and non-daemon threads.

Источник

Difference Between Daemon Threads and User Threads In Java

Daemon threads are low priority threads which always run in background and user threads are high priority threads which always run in foreground. User Thread or Non-Daemon are designed to do specific or complex task where as daemon threads are used to perform supporting tasks.

Difference Between Daemon Threads And User Threads In Java

  1. JVM doesn’t wait for daemon thread to finish but it waits for User Thread : First and foremost difference between daemon and user threads is that JVM will not wait for daemon thread to finish its task but it will wait for any active user thread. For example, one might have noticed this behavior while running Java program in NetBeans that even if the main thread has finished, the top left down button is still red, showing that Java program is still running. This is due to any user thread spawned from the main thread, but with main thread one don’t see that red dot in NetBeans.
  2. Thread Priority : The User threads are high priority as compare to daemon thread means they won’t get CPU as easily as a user thread can get.
  3. Creation of Thread : User thread is usually created by the application for executing some task concurrently. On the other hand, daemon thread is mostly created by JVM like for some garbage collection job.
  4. Termination of Thread : JVM will force daemon thread to terminate if all user threads have finished their execution but The user thread is closed by application or by itself. A user thread can keep running by the JVM running but a daemon thread cannot keep running by the JVM. This is the most critical difference between user thread and daemon thread.
  5. Usage : The daemons threads are not used for any critical task. Any important task is done by user thread. A daemon thread is generally used for some background tasks which are not critical task.

The Major Difference between User and Daemon Threads:

User Thread Daemon Thread
JVM wait until user threads to finish their work. It never exit until all user threads finish their work. The JVM will’t wait for daemon threads to finish their work. The JVM will exit as soon as all user threads finish their work.
JVM will not force to user threads for terminating, so JVM will wait for user threads to terminate themselves. If all user threads have finished their work JVM will force the daemon threads to terminate
User threads are created by the application. Mostly Daemon threads created by the JVM.
Mainly user threads are designed to do some specific task. Daemon threads are design as to support the user threads.
User threads are foreground threads. Daemon threads are background threads.
User threads are high priority threads. Daemon threads are low priority threads.
Its life independent. Its life depends on user threads.

Example: Check Thread is Daemon or not One can make a user thread as daemon thread by using setDaemon(boolean) method. In this example, thread type is being checked (User thread or Daemon thread) by using isDaemon() method. It returns true if it is daemon otherwise it returns false.

Источник

Оцените статью