Tuesday 24 June 2014

Daemon Thread

There are two types of threads user thread and daemon thread. The daemon thread is a service provider thread which runs in background to provide services to the user thread and mostly created by JVM for performing background task like Garbage collection and other house keeping tasks. Its life depends on the user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

Points to remember for Daemon Thread:

  • It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
  • 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.
  • Its life depends on user threads.
  • It is a low priority thread.

Why JVM terminates the daemon thread if there is no user thread remaining?
The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread. That is why JVM terminates the daemon thread if there is no user thread.

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.



No comments:

Post a Comment