Daemon Thread in Java

Daemon thread in Java is a thread that runs in background to perform some tasks for the program as long as the program is running. Even if daemon threads are running that doesn’t prevent JVM from shutting down.

Features of daemon thread in Java

The Java Virtual Machine exits when the only threads running are all daemon threads. So, the JVM waits only for the non-demon thread in a program to complete.

That is why daemon threads in Java are suitable for performing general tasks like clearing the in-memory cache which may be essential to a program but not the main part of the program. Even the JVM, when it starts, creates daemon threads for garbage collection and other book keeping tasks and a non-daemon main thread for executing the program. That is also the reason why JVM doesn’t wait for daemon threads to finish as daemon thread in Java is supposed to perform some background tasks for the user threads. If user threads have completed there is no sense in executing the daemon thread.

Whether a thread is daemon or not that property is inherited from the thread that spawned the other thread. Since main thread in Java is non-daemon so any thread spawned in main thread will be non-daemon.

Same way any thread created by a daemon thread is automatically a daemon thread.

If you want to mark a thread as either a daemon thread or a user thread that can be done using setDaemon(boolean on) method of the Thread class in Java.

setDamon(boolean on) can only be called before the thread has been started i.e. before calling thread.start() method. Otherwise IllegalThreadStateException is thrown.

Another method of the Thread class isDaemon() tests if thread is a daemon thread. Returns true is calling thread is a daemon thread; false otherwise.

Daemon thread Java example code

In the example code there are two thread classes DaemonThread and AnotherDaemon. Initially when a DaemonThread instance is created it would be a non-daemon thread as it is created in main thread which itself is non-daemon, later it is changed to a daemon thread using setDaemon() method. On the other hand instance of AnotherDaemon would be a daemon thread as it is created in DaemonThread which is now a daemon thread.

Output

That’s all for the topic Daemon Thread in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

One Comment

  1. Pingback: What is Hadoop - KnpCode

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.