Daemon Thread in Java

Filed Under: Java

Daemon thread in java can be useful to run some tasks in background. When we create a thread in java, by default it’s a user thread and if it’s running JVM will not terminate the program.

Daemon thread in java

When a thread is marked as daemon thread, JVM doesn’t wait it to finish to terminate the program. As soon as all the user threads are finished, JVM terminates the program as well as all the associated daemon threads.

Thread.setDaemon(true) is used to create a daemon thread in java. This method should be invoked before the thread is started otherwise it will throw IllegalThreadStateException.

We can check if a thread is daemon thread or not by calling isDaemon() method on it.

Another point is that when a thread is started, it inherits the daemon status of it’s parent thread.

Daemon Thread in Java Example

Let’s see a small example of daemon thread in java.


package com.journaldev.threads;

public class JavaDaemonThread {

    public static void main(String[] args) throws InterruptedException {
        Thread dt = new Thread(new DaemonThread(), "dt");
        dt.setDaemon(true);
        dt.start();
        //continue program
        Thread.sleep(30000);
        System.out.println("Finishing program");
    }

}

class DaemonThread implements Runnable{

    @Override
    public void run() {
        while(true){
            processSomething();
        }
    }

    private void processSomething() {
        try {
            System.out.println("Processing daemon thread");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
}

When we execute above daemon thread program, JVM creates first user thread with main() method and then a daemon thread.

When main method is finished, the program terminates and daemon thread is also shut down by JVM.

Below image shows the output of the above program.

daemon thread in java

If we don’t set the “dt” thread to be run as daemon thread, the program will never terminate even after main thread is finished it’s execution. Notice that DaemonThread is having a while true loop with thread sleep, so it will never terminate on it’s own.

Try to comment the statement to set thread as daemon thread and run the program. You will notice that program runs indefinitely and you will have to manually quit it.

Daemon Thread Usage

Usually we create a daemon thread for functionalities that are not critical to system. For example logging thread or monitoring thread to capture the system resource details and their state. If you are not okay will a thread being terminated, don’t create it as a daemon thread.

Also it’s better to avoid daemon threads for IO operations because it can cause resource leak when program just terminates and resources are not closed properly.

Reference: API Doc

Comments

  1. Anil Kumar says:

    if dt is the daemon thread then could it possible or any option to call it as user thread?
    pls let me know clearly which one is user thread and daemon thread ?
    how can we find the difference between user thread and daemon thread?

  2. Jagadeesh Verri says:

    For example logging thread or monitoring thread to capture the system resource details and their state.

    Also in the next statement , to avoid resource leaks avoid IO operations as part of Deamon threads..

    But logger thread will log the data into a file, which is a IP operation

  3. Debi says:

    Is main method user thread or daemon thread?

    1. Rohit Shekhar says:

      public static void main(String[] args) {
      System.out.println(Thread.currentThread().isDaemon());
      }

      Above code snippet prints false.

  4. Pradeep gupta says:

    why we use daemon thread? give us some scenario.

  5. Rasmi says:

    Help me in this question plz?
    Suppose I want to send messages to the customers on their birth day automatically without any logging in the system. can I achieve this by writing a daemon thread which will work in the background to send the messages.

    1. Pankaj says:

      There are several approaches for this, best way is:

      1. Write the program to check the users from database, if it’s their birthday then send email to them.
      2. Create a cronjob that will run everyday midnight or whatever time you want to send email to execute above program.

      Daemon thread is not the good approach in this case.

      1. Rasmi says:

        thank u…

  6. Kapil Agarwal says:

    Here Main method thread is a User Thread and dt is Daemon thread (as it is set to dt.setDaemon(true)).
    Now the confusion point Thread dt = new Thread(new DaemonThread(), “dt”); is because of the name of the class but it is actually a runnable thats any thread needed.

    Think of a Thread as a Worker and Runnable as a Job which a worker has to do.

    Hope its now clear the things.

  7. Mohamed says:

    Hi
    Actually I am confused which one is User Thread and which one is daemon thread?

    Thread dt = new Thread(new DaemonThread(), “dt”);
    dt.setDaemon(true);

    My understanding
    dt = deamon thread as u set dt.setDaemon(true)
    new DaemonThread = User Thread

    Would be better if you can ll DaemonThread as UserThread?

    1. Pankaj says:

      DaemonThread is a normal Runnable and dt.setDaemon(true); is the statement where it’s getting converted from user thread to daemon thread.

      1. Mohamed says:

        Thanks but still not sure in the example why u call a user thread (one which has no setDeamon to true) a deamon thread

        Thread dt = new Thread(new DaemonThread(), “dt”); — This is daeamon thread
        dt.setDaemon(true);

        My understanding
        dt = deamon thread as u set dt.setDaemon(true)
        new DaemonThread –> This is user thread you got the naming wrong!

        Would be better if you can ll DaemonThread as UserThread?

        1. Pankaj says:

          Don’t be confused, in above example dt is the daemon thread.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages