Java Daemon Thread Tutorial

In this section, we will learn what the daemon thread is and how it works in Java.

Types of Threads in Java:

In Java, a thread can be of two types:

  • User Thread
  • Daemon Thread

The way these two types of threads work is pretty much the same, with one exception:

If a thread is a daemon, the JVM might abrupt that thread without letting the thread to finish its work!

Alright, let’s move on and see each of these types of thread in a better detail.

What is User Threads?

The first type of thread that we’ve been creating so far is called the user thread.

The main aspect of a user thread is that the JVM will wait for the work of that thread to finish and then will terminate the program.

Basically, we know that a program at least has one thread that is called `main`. Now, if we add other threads in addition to the `main` one, even if the work of the `main` thread is done, the JVM will wait until the other threads finish their work and then it will terminate the program.

But this is not true for daemon threads! Alright, let’s go and see what is a daemon thread now!

What is Daemon Thread in Java?

First of all, the word `daemon` is pronounced just like the word `demon` but it has nothing to do with `demon`!

A daemon thread is basically a thread that provides a service for a user thread. Basically, these types of threads depend on user threads! Their existence is meaningless if there’s no user thread in a program!

For example, consider a user thread that asks a daemon thread to make a connection to an external resource and perhaps download a file or something similar. Now, while the daemon thread is on the task, if the user-thread dies for whatever reason, there’s no point in letting the daemon thread live! Because there’s no recipient for the work of the daemon thread!

For this reason, if in a program the JVM sees that there’s or there are only daemon threads with no user-threads, it will shut down the program without even caring whether the work of those daemon threads are done or not.

Note: the way we create a daemon thread is just like creating a user thread, with one exception, though! In order to turn a user thread into a daemon one, there’s a flag that should be turned on. We turn this flag on with the help of the `setDaemon()` method.

We will get into this method later in this section.

Difference between Daemon Threads and User Threads

Well, the purpose of the daemon thread is to provide a service for the user thread! So the user-thread is the consumer of the service that a daemon thread provides.

Now, the main difference perhaps is in the way they are treated by the JVM!

If in a program the JVM detects that all the threads are daemon, it will terminate the work of that program without even waiting for those threads to finish their work!

But if there’s even one user thread in a program, the JVM will wait for that thread to finish its work and then it will close the program.

How to create a daemon thread: Thread setDaemon() Method

As mentioned before, in order to create a daemon thread, we use a method called `setDaemon()`.

This method takes one argument, and that is a boolean value. By default, the thread that we create in a program is not daemon! So if we want to turn it into a daemon one, we can pass the value true as the argument of this method and bingo! The thread becomes a daemon one.

Note: the call to the `setDaemon()` method should happen before we call the `start()` method on that thread. If we call the method after calling the `start()` method, we will get `IllegalThreadStateException` exception.

Example: using setDaemon() method

public class Main {
    public static Thread t1;
    public static Thread t2;
    public static void main(String[] args) {
        Main main = new Main();
        t1 = new Thread(main::run, "Thread-one");
        t1.setDaemon(true);
        t1.start();
        System.out.println("The main thread finished its work... ");

    }
    public synchronized void run() {
        System.out.println("The daemon thread started... ");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("You'll never see this message!");

    }
}

Output:

The main thread finished its work...

The daemon thread started...

Note that because the `t1` is a daemon thread, after the main thread finished its work, the JVM didn’t wait for this `t1` thread to completely execute the `run()` method and terminated the program.

Thread isDaemon() method

The isDaemon() method is used to see if a thread is daemon or not.

The return value of this method is of type boolean. If the value is true, it means the target thread is a daemon thread. Otherwise, if the value false was returned, that means the thread is not a daemon one.

Example: using isDaemon() method

public class Main {
    public static Thread t1;
    public static Thread t2;
    public static void main(String[] args) {
        Main main = new Main();
        t1 = new Thread(main::run, "Thread-one");
        t1.setDaemon(true);
        t1.start();
        System.out.println("Is the t1 a daemon thread?: "+t1.isDaemon());
        System.out.println("The main thread finished its work... ");

    }
    public synchronized void run() {
        System.out.println("The daemon thread started... ");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("You'll never see this message!");

    }
}

Output:

The daemon thread started...

Is the t1 a daemon thread?: true

The main thread finished its work...
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies