Daemon Thread in java


A daemon thread is a thread that is considered doing some tasks in the background like handling requests or various chronjobs that can exist in an application.

When your program only have damon threads remaining it will exit. That's because usually these threads work together with normal threads and provide background handling of events.

You can specify that a Thread is a demon one by using setDaemon method, they usually don't exit, neither they are interrupted.. they just stop when application stops.

The core difference between user threads and daemon threads is that the JVM will only shut down a program when all user threads have terminated. Daemon threads are terminated by the JVM when there are no longer any user threads running, including the main thread of execution.

Normal Thread
Program 1#
    
public class DaemonThreadTest {

    public static void main(String[] args) {
        new WorkerThread().start() ;
        try {
            Thread.sleep(7500);
        } catch (InterruptedException e) {}
        System.out.println("Main Thread ending") ;
    }

}
class WorkerThread extends Thread {

    public WorkerThread() {
        
    }

    public void run() {
        int count=0 ;
        while (true) {
             System.out.println("Hello from Worker "+count++) ;
            try {
                sleep(5000);
            } catch (InterruptedException e) {}
        }
    }
}
Out put :

Hello from Worker 0
Hello from Worker 1
Main Thread ending
Hello from Worker 2
Hello from Worker 3
Hello from Worker 4
Hello from Worker 5 ... never end

Program 2#
Daemon Thread
 
public class DaemonThreadTest {

    public static void main(String[] args) {
        new WorkerThread().start() ;
        try {
            Thread.sleep(7500);
        } catch (InterruptedException e) {}
        System.out.println("Main Thread ending") ;
    }

}
class WorkerThread extends Thread {

    public WorkerThread() {
        setDaemon(true) ;  
    }

    public void run() {
        int count=0 ;
        while (true) {
             System.out.println("Hello from Worker "+count++) ;
            try {
                sleep(5000);
            } catch (InterruptedException e) {}
        }
    }
}
Out put

Hello from Worker 0
Hello from Worker 1
Main Thread ending
Above example - Program 2# we modified the WorkedThread as Dameon thread by  adding setDaemon(true).  Daemon threads are terminated by the JVM when there are no longer any user threads running, so after executing main thread (System.out.println("Main Thread ending") ;) the daemon thread will terminate by JVM, Where in Program 1- workerThread is not daemon thread, so the thread will keep on running.


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...