Wednesday, February 10, 2016

Daemon Thread in java

Introduction:

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(){
@Override
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Executing Daemon Thread");
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t.setDaemon(true); // Thread becomes daemon thread here
t.start();
System.out.println("Exiting Main Thread");
}
}

Here is the sample output:

Output1:
Entering Main Thread
Exiting Main Thread

Output2:
Entering Main Thread
Exiting Main Thread
Executing Daemon Thread
Executing Daemon Thread

Explanation

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