Sunday 25 December 2016

Daemon Thread in Java


In Java, Daemon Threads are one of the types of thread which does not prevent Java Virtual Machine (JVM) from exiting.
The main purpose of daemon thread is to execute background task especially in case of some routine periodic task or work. With JVM exits, daemon thread also dies.

How to create a Daemon Thread in Java:

By setting a thread.setDaemon(true), a thread becomes a daemon thread. However, you can only set this value before the thread start.

Code Example:

public class DaemonThread {

public static void main(String[] args) {
System.out.println("Entering Main Thread");
Thread t = new Thread(new Runnable(){
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Executing Daemon Thread");
try {
} catch (InterruptedException e) {
t.setDaemon(true); // Thread becomes daemon thread here
System.out.println("Exiting Main Thread");

Here is the sample output:

Entering Main Thread
Exiting Main Thread

Entering Main Thread
Exiting Main Thread
Executing Daemon Thread
Executing Daemon Thread


In the above code example, main thread is spawning a daemon thread, Here main thread is the only non-deamon thread. As soon as the main thread execution completes, JVM exits and daemon thread dies alongwith.

The above code example and output illustrates the following:
  • JVM doesn't wait for the daemon thread to complete its task
  • Daemon thread dies as soon as JVM exits

Finding if the thread is daemon or not:

To know if a thread is daemon or not, you can check with Thread.isDeamon(). If returns true, the thread is daemon.

No comments:

Post a Comment