Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
daemon
thread

How to check if a thread is a daemon thread

abhilash

Overview

Daemon threads are low-priority threads whose purpose is to provide services to user threads.

Daemon threads are only required while user threads are operating. They will not prevent the JVM from quitting after all user threads complete their execution.

Infinite loops, common in daemon threads, do not cause issues since no code, including final blocks, will be executed until all user threads have completed their execution. As a result, daemon threads should not be used for I/O activities.

The isDaemon() method of the Thread class is used to check if a given thread is a daemon thread or not.

Syntax

public final boolean isDaemon()

Parameters

The method has no parameters.

Return value

The method returns true if the current thread is a daemon thread. Otherwise, it returns false.

Code

public class Main{

    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            if(Thread.currentThread().isDaemon()) System.out.println(Thread.currentThread().getName() + " is a daemon thread");
            else System.out.println(Thread.currentThread().getName() + " is not a daemon thread");
        };
        Thread daemonThread = new Thread(runnable);
        daemonThread.setName("daemon-thread");
        daemonThread.setDaemon(true);
        Thread notDaemonThread = new Thread(runnable);
        notDaemonThread.setName("not-daemon-thread");
        daemonThread.start();
        notDaemonThread.start();
        Thread.sleep(1000);
    }
}
Implementation of the isDaemon() method

Explanation

  • Lines 4 to 7: We create an implementation of the Runnable interface, that is, a runnable that prints whether the current thread is a daemon thread or not with the help of the isDaemon() method.
  • Line 8: We create a thread with the help of a runnable called daemonThread.
  • Line 9: We name the daemonThread thread as daemon-thread.
  • Line 10: We make the daemonThread thread a daemon thread using the setDaemon() method.
  • Line 11: We create another thread with the help of a runnable called notDaemonThread.
  • Line 12: We name the notDaemonThread thread as "not-daemon-thread".
  • Lines 13 and 14: We start the threads daemonThread and notDaemonThread using the start() method.
  • Line 15: The main thread is made to sleep for one second.

RELATED TAGS

java
communitycreator
daemon
thread
RELATED COURSES

View all Courses

Keep Exploring