Quantcast
Channel: What is a daemon thread in Java? - Stack Overflow
Viewing all articles
Browse latest Browse all 28

Answer by Aniket Thakur for What is a daemon thread in Java?

$
0
0

Daemon thread in Java are those thread which runs in background and mostly created by JVM for performing background task like Garbage collection and other house keeping tasks.

Points to Note :

  1. Any thread created by main thread, which runs 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 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 corresponding Thread is already started and running.

Difference between Daemon and Non Daemon thread in Java :

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

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


Viewing all articles
Browse latest Browse all 28

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>