Tuesday, 25 February 2014

Daemon Threads and User Threads in java

Daemon vs Non-Daemon threads:
Thread has two types, namely daemon threads and non-daemon threads (user threads). Daemon threads will run in background and JVM does not wait for the daemon threads to complete. In contrast JVM waits until all the non-daemon threads or user threads to complete.
By default the main thread is the non-daemon thread and any threads created by main thread will be a non-daemon thread because threads inherit its parent’s properties.
To convert user thread to a daemon thread use the following call in java,
threadName.setDaemon(“true”);

Example of Daemon threads: Garbage collector operation is done by daemon threads and it runs in background.
Code
package thread;
/**
* @author Sivaranjani D
*
*/
public class DaemonThreadExample {
public static void main(String args[]){
Thread t = new Thread(new Runnable() {

public void run() {
while(true){
System.out.println("Daemon thread is running");
}

}
});

t.setDaemon(true); // turn this off and on to see the difference
t.start();
System.out.println(Thread.currentThread().getName());
}
}

When you turn on the setDaemon to true, you can see only some 4 to five time the "Daemon thread is running" statement printing. Because while Daemon thread is running JVM don't wait and it terminates once the main non-daemon thread completes. But when you turn that off, the JVM never terminate and waits for the non ending loop of the non-daemon thread.

No comments:

Post a Comment