What is Daemon Thread in Java
Daemon thread in Java is a special thread which runs in background and has low priority.
In java, the Daemon thread does not prevent JVM from exiting when the program finishes, but the thread is still running. For example, garbage collection. Basically Daemon thread is a process which runs in the background, we call it as system thread as well. To know more about threads in java see this tutorial first.
Daemon Thread Methods
There are two methods used
- void setDaemon(boolean value): This setDaemon() method is used to create the current thread/user thread as daemon thread.
- boolean isDaemon(): This method is used to check whether the current thread is daemon or not. It returns true if the current thread is daemon, otherwise it returns false.
Daemon Thread in Java Example
How to create daemon thread in java
Let’s see the code example:
package com.slb.thread;
public class DaemonThreadExample extends Thread{
@Override
public void run() {
System.out.println("running...");
System.out.println(this.getName());
System.out.println("is this daemon thread ? :" + this.isDaemon());
}
//will first create one user thread and then will create another one for daemon
public static void main(String[] args) {
DaemonThreadExample userThread = new DaemonThreadExample();
DaemonThreadExample daemonThread = new DaemonThreadExample();
daemonThread.setDaemon(true);
userThread.setName("USER THREAD");
daemonThread.setName("DAEMON THREAD");
userThread.start();
daemonThread.start();
}
}
In the above example, we have created two threads, one is for user and another is for daemon thread.
For user thread we are not setting anything apart from name using setName() method, but for another thread for which we need to make it as daemon, we are setting it using setDaemon(true) to make it daemon thread.
In run method we are checking whether the thread is daemon or not by using isDaemon() method which will return true/false based on if it’s daemon or not.
Priority of Daemon Thread
Since daemon threads are low-priority ones as these are set by JVM. Let’s understand that with example.
package com.slb.thread;
public class DaemonThreadExample extends Thread{
@Override
public void run() {
System.out.println("running...");
// System.out.println(this.getName());
// System.out.println("is this daemon thread ? :" + this.isDaemon());
System.out.println("PRIORITY OF "+this.getName() +" THREAD : " + this.getPriority());
}
//will first create one user thread and then will create another one for daemon
public static void main(String[] args) {
DaemonThreadExample userThread1 = new DaemonThreadExample();
DaemonThreadExample daemonThread = new DaemonThreadExample();
DaemonThreadExample userThread2 = new DaemonThreadExample();
DaemonThreadExample userThread3 = new DaemonThreadExample();
DaemonThreadExample daemonThread2 = new DaemonThreadExample();
daemonThread.setDaemon(true);
daemonThread2.setDaemon(true);
userThread1.setName("USER THREAD-1");
userThread2.setName("USER THREAD-2");
userThread3.setName("USER THREAD-3");
daemonThread.setName("DAEMON THREAD 1 ");
daemonThread2.setName("DAEMON THREAD 2 ");
userThread1.start();
daemonThread.start();
userThread2.start();
userThread3.start();
System.out.println("checking main thread is daemon or not");
System.out.println(Thread.currentThread().isDaemon());
}
}
Output of the above thread executions:
checking main thread is daemon or not
running...
running...
running...
running...
false
PRIORITY OF USER THREAD-1 THREAD : 5
PRIORITY OF DAEMON THREAD 1 THREAD : 5
PRIORITY OF USER THREAD-3 THREAD : 5
PRIORITY OF USER THREAD-2 THREAD : 5
Process finished with exit code 0
You can access the complete code here at SLB-GITHUB
Advantages of using daemon thread
Daemon threads in Java are background threads that provide services to other threads without interfering with JVM exit when all user threads have completed executing. Their advantages are:
Effectiveness:
Daemon threads can help increase efficiency when performing background tasks that don’t require user interaction. Because these daemon threads don’t prevent the JVM from exiting, they can help your application make the best use of its resources by freeing them up when no longer required.
Timers and schedulers:
Daemon threads can be used to implement timers and schedulers that run in the background without disrupting your main application thread, helping improve responsiveness and performance of your application. This can improve responsiveness and performance.
Garbage Collection:
When no longer required, the JVM automatically clears away memory used by daemon threads that no longer require it, helping prevent memory leaks and improve overall application performance. This feature helps prevent leakage of precious RAM storage resources as well as enhance overall application performance.
Loggers:
Daemon threads can be used to log events without interfering with the main application thread, which can help improve reliability and stability in your app.
Service Providers:
Daemon threads can be used to provide services like database connection pooling, email sending or file synchronization in the background – this can enhance both scalability and responsiveness for your application.
Overall, daemon threads in Java can significantly enhance the efficiency, performance, and reliability of your app. They’re perfect for handling background tasks that do not need user interaction and providing services such as timers, schedulers, loggers, or service providers.
FAQ on Daemon Thread
What is a Daemon Thread in Java?
A daemon thread is a type of background thread in Java that runs invisibly and provides services to other threads; they do not prevent the JVM from exiting when all user threads have completed executing.
How do I create a daemon thread in Java?
A daemon thread can be created in Java by calling the setDaemon() method on a Thread object with true as its argument. This should be called before starting up the thread itself.
What tasks can Daemon Threads Perform?
Daemon threads can perform many different types of tasks, from logging application events and running timers and schedulers, to providing services like database connection pooling, email sending or file synchronization – among many others.
Can I convert an existing thread to a daemon thread in Java?
Unfortunately, no. In order to set an existing thread as a daemon thread in Java, the setDaemon() method must first be invoked prior to starting it up.
What happens to daemon threads when the JVM exits?
Once a JVM exits, all daemon threads will be abruptly terminated – thus it is wise to complete any necessary cleanup tasks prior to shutting off the JVM.
How can I check if a thread in Java is a daemon thread?
The isDaemon() method on a Thread object provides the capability of doing exactly this – returning true when applicable and false otherwise.
Are daemon threads an alternative to regular threads in Java?
No. Daemon threads should only be used as background services and should never be relied upon to perform tasks that require user interactions or have long running times.
Can a daemon thread stop other threads in Java?
No, daemon threads in Java cannot stop other threads from running concurrently. Daemons provide services to other threads without altering their behavior in any way.
Can I change the priority of a daemon thread in Java?
Yes, using the setPriority() method on a Thread object you can alter its priority setting accordingly; just ensure that this doesn’t alter other threads within your application as this could have negative implications.
Are daemon threads always running in the background in Java?
No, Java’s daemon threads do not always run in the background – they only execute when user threads are running in an application and when all user threads have completed execution the JVM exits and all daemon threads are terminated.
Can I interrupt a daemon thread in Java?
yes, using the interrupt() method on a Thread object you can stop a daemon thread running in an application from running by calling its interrupt() method and invoking its Stop method. Just ensure that any interruption of another thread doesn’t affect their behavior too drastically before taking such steps.