Skip to content
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

Simplified Learning Blog

Learning made easy

  • Java
    • Core Java Tutorial
    • Java 8
    • What is Rest API in java
    • Spring Framework
    • Type Casting in Java | 2 types Implicit and explicit casting
    • Spring Boot Tutorial
      • Spring Boot Rest API Example complete guide
    • Top 50 Java Interview Questions
    • JUnit 5 Tutorial
      • Assertall in JUnit 5
      • Assertions in JUnit 5
    • Java Thread Tutorials
      • How to create thread in Java
      • Multithreading in java
      • Daemon Thread in Java | How to create daemon thread in java
      • Top 40+ Multithreading interview questions
  • AWS
    • What is AWS (Amazon Web Services)
    • AWS IAM (Identity and Access Management)
    • AWS SNS | What is SNS
    • What is SQS | AWS SQS (Simple Queue Service)
    • What is AWS Lambda
    • Top 10 AWS Lambda interview questions
  • Java Codes
  • Software Architecture
    • Software Architecture Performance
    • Performance Principles of Software Architecture
    • System Performance Objective
  • Spring Boot Tutorial
  • Tools
    • JSON Formatter and Validator
  • Tech Blogs
    • Java 21 New Features
    • Is Java Dead? Is java dead, 2023 ?
    • New Features in Java 17
  • Toggle search form

Daemon Thread in Java | How to create daemon thread in java

Posted on February 12, 2023April 27, 2023 By Admin No Comments on Daemon Thread in Java | How to create daemon thread in java

What is Daemon Thread in Java

Daemon thread in Java is a special thread which runs in background and has low priority.

Table of Contents

Toggle
  • What is Daemon Thread in Java
  • Daemon Thread Methods
  • Daemon Thread in Java Example
    • How to create daemon thread in java
  • Priority of Daemon Thread
  • Advantages of using daemon thread
    • Effectiveness:
    • Timers and schedulers:
    • Garbage Collection:
    • Loggers:
    • Service Providers:
  • FAQ on Daemon Thread

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

  1. void setDaemon(boolean value): This setDaemon() method is used to create the current thread/user thread as daemon thread.
  2. 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.

Related

Java Threads

Post navigation

Previous Post: How to create thread in Java
Next Post: Is Java Dead? Is java dead, 2023 ?

More Related Articles

Java Thread Tutorials Java Threads
How to create thread in Java Java Threads
Multithreading in java Java Threads
Top 40+ Multithreading interview questions Java Threads
Spring Boot Rest API Example complete guide Java Threads

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Top 50 Java Coding Interview Questions and Answers (2025 Updated)
  • Java Record Class Explained: Simple, Immutable Data Carriers
  • Java Convert int to String – 5+ Methods with Examples
  • String to Integer Conversion in Java | Java convert string to int
  • PDF to JSON Convertor

Recent Comments

No comments to show.

Copyright © 2025 Simplified Learning Blog.

Powered by PressBook Green WordPress theme