BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Daemon thread in Java with example

By Chaitanya Singh | Filed Under: java

Daemon thread is a low priority thread (in context of JVM) that runs in background to perform tasks such as garbage collection (gc) etc., they do not prevent the JVM from exiting (even if the daemon thread itself is running) when all the user threads (non-daemon threads) finish their execution. JVM terminates itself when all user threads (non-daemon threads) finish their execution, JVM does not care whether Daemon thread is running or not, if JVM finds running daemon thread (upon completion of user threads), it terminates the thread and after that shutdown itself.

Properties of Daemon threads:

  1. A newly created thread inherits the daemon status of its parent. That’s the reason all threads created inside main method (child threads of main thread) are non-daemon by default, because main thread is non-daemon. However you can make a user thread to Daemon by using setDaemon() method of thread class.
    Just a quick note on main thread: When the JVM starts, it creates a thread called “Main”. Your program will run on this thread, unless you create additional threads yourself. The first thing the “Main” thread does is to look for your static void main (String args[]) method and invoke it. That is the entry-point to your program. If you create additional threads in the main method those threads would be the child threads of main thread.
  2. Methods of Thread class that are related to Daemon threads:
    public void setDaemon(boolean status): This method is used for making a user thread to Daemon thread or vice versa. For example if I have a user thread t then t.setDaemon(true) would make it Daemon thread. On the other hand if I have a Daemon thread td then by calling td.setDaemon(false) would make it normal thread(user thread/non-daemon thread).
    public boolean isDaemon(): This method is used for checking the status of a thread. It returns true if the thread is Daemon else it returns false.
  3. setDaemon() method can only be called before starting the thread. This method would throw IllegalThreadStateException if you call this method after Thread.start() method. (refer the example)

Daemon thread examples

Example 1: DaemonThreadExample1.java
This example is to demonstrate the usage of setDaemon() and isDaemon() method.

public class DaemonThreadExample1 extends Thread{

   public void run(){  
		
	  // Checking whether the thread is Daemon or not
	  if(Thread.currentThread().isDaemon()){ 
	      System.out.println("Daemon thread executing");  
	  }  
	  else{  
	      System.out.println("user(normal) thread executing");  
          }  
   }  
   public static void main(String[] args){  
	 /* Creating two threads: by default they are 
	  * user threads (non-daemon threads)
	  */
	 DaemonThreadExample1 t1=new DaemonThreadExample1();
	 DaemonThreadExample1 t2=new DaemonThreadExample1();   
			 
	 //Making user thread t1 to Daemon
        t1.setDaemon(true);
		     
        //starting both the threads 
        t1.start(); 
        t2.start();  
   } 
}

Output:

Daemon thread executing
user(normal) thread executing

Example 2: DaemonThreadEx2.java
If you call the setDaemon() method after starting the thread (start() method), it would throw IllegalThreadStateException. This clearly means that you can call setDaemon() method only before starting a thread.

public class DaemonThreadEx2 extends Thread {

   public void run(){  
	  System.out.println("Thread is running");   
   }  
		  
    public static void main(String[] args){  
	 DaemonThreadEx2 t1=new DaemonThreadEx2();  
         t1.start();  
	 // It will throw IllegalThreadStateException
	 t1.setDaemon(true); 
    } 
}

Output:

Exception in thread "main" Thread is running
java.lang.IllegalThreadStateException
	at java.lang.Thread.setDaemon(Unknown Source)
	at beginnersbook.com.DaemonThreadEx2.main(DaemonThreadEx2.java:13)

Difference between Daemon threads and non-Daemon thread (user thread)

The main difference between Daemon thread and user threads is that the JVM does not wait for Daemon thread before exiting while it waits for user threads, it does not exit until unless all the user threads finish their execution.

Comments

  1. Karthik says

    August 14, 2015 at 12:36 AM

    Simplest yet one of the best tutorials. Thanks on the effort you have spent.

    Reply
  2. Zafar Iqbal says

    September 22, 2015 at 7:17 AM

    Good work. Excellent explain!

    Reply
  3. Gary says

    December 14, 2015 at 4:30 PM

    Hello, I’m sorry this may appear a silly question, but, it sounds like according to definition described, the daemon thread does not continue running in the background, which is what it should do. the JVM will terminate the daemon thread then shutdown itself. I guess I am a little confused, because daemons are to stay alive and keep running in background. I need this behavior. Can someone help explain this to me? It seems that one can make the user thread will stay alive and the daemon will terminate by nature. I need to create a daemon that will continue to monitor things and run continuously in the background, of course go to sleep for 3 minutes and then wake up, do its thing, then go back to sleep. over and over again. What am I missing? thanks so much!
    Gary

    Reply
  4. Yash says

    December 24, 2015 at 1:35 PM

    Which exits first, Daemon thread or JVM?

    Reply
    • iman shirali says

      July 22, 2016 at 11:32 AM

      if JVM finds running daemon thread (upon completion of user threads), it terminates the thread and after that shutdown itself.

      Reply
    • Daksh Gargas says

      February 19, 2017 at 12:03 PM

      Daemon thread works in the background as stated earlier, so when the user(normal) thread(s) is/are done with their jobs, then JVM abruptly terminates Daemon thread.
      So as soon as all non-daemon exits, JVM shuts down all the daemons immediately, without any of the formalities you might have come to expect.

      Reply

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap