Daemon Thread in Java

Daemon thread is a service provider thread with low priority. Normally, it is used to provide service like background supporting tasks (garbage collection etc.). Its life depends on normal non-daemon threads. If all non-daemon threads are not running, the daemon thread will terminate.

Two methods are related to Daemon thread are:
public void setDaemon(boolean status) which can only be called before the thread start.
public boolean isDaemon()

Difference between daemon thread and normal thread

  1. The child of a daemon thread is always daemon thread
  2. When the JVM shuts down, it does not wait for daemon threads to finish. Daemon thread will be abandoned. If there is a finally block in the daemon thread code, it is not guaranteed to be executed. In addition, stacks are not unwounded and JVM just exits.

The following example code will shows how a daemon thread is created

The output:

The following example code will shows that once all non-dameon threads executed, the JVM will shut down without waiting for the daemon thread. The daemon thread in the example will be abandoned.

The output:

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInShare on RedditShare on StumbleUponEmail this to someoneShare on TumblrDigg this

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">