Friday, May 26, 2023

What is Daemon thread in Java and Difference to Non daemon thread - Tutorial Example

Daemon thread in Java is those thread that runs in the background and is mostly created by JVM for performing background tasks like Garbage collection and other housekeeping tasks. The difference between Daemon and Non-Daemon (User Threads)  is also an interesting multi-threading interview question, which is asked mostly on fresher level java interviews. In one line main difference between daemon thread and user thread is that as soon as all user threads finish execution java program or JVM terminates itself, JVM doesn't wait for daemon thread to finish their execution.


As soon as the last non-daemon thread is finished JVM terminates no matter how many Daemon threads exist or running inside JVM. In this java thread tutorial, we will see examples of Daemon threads in Java and some more differences between Daemon and non-daemon threads.


What is Daemon thread in Java and Difference to Non daemon thread - Tutorial Example



Important points about Daemon threads in Java

1. Any thread created by the main thread, which runs the main method in Java is by default non-daemon because Thread inherits its daemon nature from the Thread which creates it i.e. parent Thread and since the main thread is a non-daemon thread, any other thread created from it will remain non-daemon until explicitly made daemon by calling setDaemon(true).

2. Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in Java. It will throw IllegalThreadStateException if the corresponding Thread is already started and running.

3. Daemon Threads are suitable for doing background jobs like housekeeping, Though I have yet to use it for any practical purpose in application code. let us know if you have used daemon thread in your java application for any practical purpose.



Difference between Daemon and Non-Daemon thread in Java

here are a couple of differences between daemon and user thread in Java:

1) JVM doesn't wait for any daemon thread to finish before existing.

2) Daemon Thread is treated differently than User Thread when JVM terminates, finally, blocks are not called, Stacks are not unwounded and JVM just exits.

And, if you need more differences, here is a nice table which shows all the difference between a daemon thread and a normal thread in Java:





Daemon Thread Example in Java

Here is a code example of a daemon thread in java. we make a user thread daemon by calling setDaemon(true) and every time you run you will see a variable number of print statements related to "daemon thread is running" you will never see print statement written in finally block because finally will not be called.

public class DaemonThreadExample {

    public static void main(String args[]){
   
       Thread daemonThread = new Thread(new Runnable(){
            @Override
           public void run(){
               try{
               while(true){
                   System.out.println("Daemon thread is running");
               }
                 
               }catch(Exception e){
                 
               }finally{
                   System.out.println("Daemon Thread exiting"); //never called
               }
           }
       }, "Daemon-Thread");
     
       daemonThread.setDaemon(true); //making this thread daemon
       daemonThread.start();
     
     
}

Output:
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running
Daemon thread is running

That’s all on What is Daemon Thread in Java and the difference between Daemon and non-daemon thread in Java with code example of Daemon thread in Java. JVM also uses daemon thread for Garbage collection.


Other Java tutorial on Threads you may like

8 comments :

Srujan kumar Gulla said...

Hi Author,

I am a great fan of this blogspot.. your java articles touch such nice topics but I would suggest you please not have spelling mistakes because of fast typing or any other reason. please write in a MS word or some app which does spell check.

It makes your blog that much better.

Ex: "perfuming task", "stuff. difference", "questions .Main" There are other typo's. Please don't take it negative way.

Thanks for writing such nice blogs on java.

Julien Brightside said...

Useful information I`d say. THanks.

Unknown said...

Finally block may not execute .
ref - http://stackoverflow.com/questions/464098/does-a-finally-block-always-run

Unknown said...

JVM doesn't wait for any daemon thread to finish before existing.
In the above line, it's exiting not existing.

Unknown said...

Hi Javin,
Their should be small connection to be made in the program, the displayed output is valid only if the thread runs as a non-deamon.
Once you make it as a deamon thread, since their are no other user threads running, the jvm terminates itself without displaying any output.
Please correct it....

Anonymous said...

Daemon will terminate when all non-dameon threads terminate.

Sir, is this statement true

javin paul said...

Yes, that's correct, Daemon thread will automatically terminate when all user thread are done.

Unknown said...

Yes

Post a Comment