Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Daemon Thread
Next article icon

Java Daemon Thread

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, daemon threads are low-priority threads that run in the background to perform tasks such as garbage collection or provide services to user threads. The life of a daemon thread depends on the mercy of user threads, meaning that when all user threads finish their execution, the Java Virtual Machine (JVM) automatically terminates the daemon thread.

To put it simply, daemon threads serve user threads by handling background tasks and have no role other than supporting the main execution.

Some examples of daemon threads in Java include garbage collection (gc) and finalizer. These threads work silently in the background, performing tasks that support the main execution without interfering with the user's operations.

Properties of Java Daemon Thread

Aspect

Description

No Preventing JVM Exit

Daemon threads cannot prevent the JVM from exiting when all user threads finish their execution. If all user threads complete their tasks, the JVM terminates itself, regardless of whether any daemon threads are running.

Automatic Termination

If the JVM detects a running daemon thread, it terminates the thread and subsequently shuts it down. The JVM does not check if the daemon thread is actively running; it terminates it regardless.

Low Priority

Daemon threads have the lowest priority among all threads in Java.

Default Nature of Daemon Thread

By default, the main thread is always a non-daemon thread. However, for all other threads, their daemon nature is inherited from their parent thread. If the parent thread is a daemon, the child thread is also a daemon, and if the parent thread is a non-daemon, the child thread is also a non-daemon.

Note: Whenever the last non-daemon thread terminates, all the daemon threads will be terminated automatically.

Methods of Daemon Thread

1. setDaemon(boolean status)

This method marks the current thread as a daemon thread or user thread. Setting a user thread as a daemon can be done using the'tU.setDaemon(true)', while setting a daemon thread as a user thread can be done using the 'tD.setDaemon(false)'.

Syntax: 

public final void setDaemon(boolean on)

Parameter: on: If true, marks this thread as a daemon thread.

Exceptions:

  • IllegalThreadStateException: if only this thread is active.
  • SecurityException: if the current thread cannot modify this thread.

Example:

Java
// Using setDaemon() Method  // Class extending Thread Class class DaemonThread extends Thread{     // Override the run Method     @Override     public void run(){       System.out.println("Running the Daemon Thread");     } }  // Driver Class public class Geeks  {   public static void main (String[] args) {       DaemonThread t1 = new DaemonThread();         t1.setDaemon(true);                t1.start();   } } 

Note: Yes, it will not show the output as JVM shuts down before the run() method is executed. The solution of the Problem is mentioned below after the isDaemon() method.

2. isDaemon()

This method is used to check that the current thread is a daemon. It returns true if the thread is Daemon. Else, it returns false. 

Syntax: 

public final boolean isDaemon()

Returns: This method returns true if this thread is a daemon thread; false otherwise

Example:

Java
// Usage of setDaemon() and isDaemon() method class DaemonThread extends Thread {   	// Changing the name of Threads     public DaemonThread(String name) {         super(name);     }    	// Overriding the run method     public void run()     {         // Checking whether the thread is Daemon or not         if(Thread.currentThread().isDaemon()) {             System.out.println(getName() + " is Daemon thread");         }         else {             System.out.println(getName() + " is User thread");         }     } }  // Driver Class public class Geeks {     public static void main(String[] args)     {         DaemonThread t1 = new DaemonThread("t1");         DaemonThread t2 = new DaemonThread("t2");         DaemonThread t3 = new DaemonThread("t3");              // Setting user thread t1 to Daemon         t1.setDaemon(true);                      // Starting first 2 threads         t1.start();         t2.start();          // Setting user thread t3 to Daemon         t3.setDaemon(true);         t3.start();             } } 

Output
t1 is Daemon thread t2 is User thread 

Common Issues with Daemon Threads 

Case 1: Output not Printed

This case arises when main thread which is not a Daemon Thread is executed and after it's execution JVM stops working so the daemon thread is not executed.

Solution: To, avoid such conditions we need to make main thread sleep for few seconds so that daemon thread is executed.

Example:

Java
// Class extending Thread Class class DaemonThread extends Thread {        // Override the run Method     @Override     public void run(){       System.out.println("Running the Daemon Thread");     } }  // Driver Class public class Geeks  {   	public static void main (String[] args)    	{       	DaemonThread t1 = new DaemonThread();       	t1.setDaemon(true);              	t1.start();              	// Ensuring JVM doesn't terminate immediately       	try {             Thread.sleep(100);          } catch (InterruptedException e) {             e.printStackTrace();         }   } } 

Output
Running the Daemon Thread 

So, the Output is finally printing , now let's move to the next issue.

Case 2: State Changed After Starting a Thread

If you call the setDaemon() method after starting the thread, it would throw IllegalThreadStateException.

Runtime exception thrown in such Case: 

Exception in thread "main" java.lang.IllegalThreadStateException     at java.lang.Thread.setDaemon(Thread.java:1352)     at DaemonThread.main(DaemonThread.java:19)

Solution:

Java
// Usage of exception in Daemon() Thread  // Class Extending Thread Class class DaemonThread extends Thread {     public DaemonThread(String name) {         super(name);     }         	// Override the run method     public void run()     {         System.out.println("Thread name: "                             + Thread.currentThread().getName());                	System.out.println("Check if its DaemonThread: "                             + Thread.currentThread().isDaemon());     } }  // Main Class public class Geeks {       public static void main(String[] args)     {         DaemonThread t1 = new DaemonThread("t1");         DaemonThread t2 = new DaemonThread("t2");          try {             t1.start();                      // Exception as the thread is already started             t1.setDaemon(true);                      t2.start();         } catch (IllegalThreadStateException e) {             System.out.println("Illegal Thread State Exception Thrown");         }              } } 

Output
Illegal Thread State Exception Thrown Thread name: t1 Check if its DaemonThread: false 

This clearly shows that we cannot call the setDaemon() method after starting the thread. 

Note: the above try catch can save you from throwing exception cases. But, the best solution for this is to avoid such conditions.

Daemon vs User Threads

  • Priority: When only daemon threads remain in a process, the JVM exits. This makes sense because when only daemon threads are running, there is no need for a daemon thread to provide a service to another thread.
  • Usage: daemon threads are primarily used to provide background support to user threads. They handle tasks that support the main execution without interfering with the user's operations.

Next Article
Java Daemon Thread

K

kartik
Improve
Article Tags :
  • Misc
  • Java
  • Java-Multithreading
  • java-advanced
Practice Tags :
  • Java
  • Misc

Similar Reads

    Multithreading in Java
    Multithreading is a Java feature that allows the concurrent execution of two or more parts of a program for maximum utilization of the CPU. Each part of such a program is called a thread. So, threads are lightweight processes within a process.Different Ways to Create ThreadsThreads can be created by
    3 min read
    Lifecycle and States of a Thread in Java
    A thread in Java can exist in any one of the following states at any given time. A thread lies only in one of the shown states at any instant:New StateRunnable StateBlocked StateWaiting StateTimed Waiting StateTerminated StateThe diagram below represents various states of a thread at any instant:Lif
    5 min read
    Main thread in Java
    Java provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution.When a Java program starts up, one thread begins running i
    4 min read
    Java Concurrency - yield(), sleep() and join() Methods
    In this article, we will learn what is yield(), join(), and sleep() methods in Java and what is the basic difference between these three. First, we will see the basic introduction of all these three methods, and then we compare these three. We can prevent the execution of a thread by using one of th
    5 min read
    Inter-thread Communication in Java
    Inter-thread communication in Java is a mechanism in which a thread is paused from running in its critical section, and another thread is allowed to enter (or lock) the same critical section to be executed.Note: Inter-thread communication is also known as Cooperation in Java.What is Polling, and Wha
    6 min read
    Java Thread Class
    Thread is a line of execution within a program. Each program can have multiple associated threads. Each thread has a priority which is used by the thread scheduler to determine which thread must run first. Java provides a thread class that has various method calls to manage the behavior of threads b
    5 min read
    What does start() function do in multithreading in Java?
    We have discussed that Java threads are typically created using one of the two methods : (1) Extending thread class. (2) Implementing RunnableIn both the approaches, we override the run() function, but we start a thread by calling the start() function. So why don't we directly call the overridden ru
    2 min read
    Java Thread Priority in Multithreading
    Java being Object-Oriented works within a Multithreading environment in which the thread scheduler assigns the processor to a thread based on the priority of the thread. Whenever we create a thread in Java, it always has some priority assigned to it. Priority can either be given by JVM while creatin
    5 min read
    Joining Threads in Java
    java.lang.Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is terminated before the next instruction is executed by the program. If th
    3 min read
    Java Naming a Thread and Fetching Name of Current Thread
    A thread can be referred to as a lightweight process. Assigning descriptive names to threads enhances code readability and simplifies debugging. Now let us discuss the different ways to name a thread in Java.Methods to Set the Thread NameThere are two ways by which we can set the name either be it d
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences