Saturday, April 4, 2015

Deamon Thread in Java


Daemon Thread in Java


Interview questions/points on daemon thread:
  1.  A daemon thread is a thread, which does not prevent the JVM from exiting when the program finishes but the thread is still running.
  2.  Its sole purpose is serving for user threads (It provides services to user threads for background supporting tasks).
  3. Example for daemon threads: Garbage Collection 

 For more details about Daemon Thread see below:

Daemon thread in java is a service provider thread that provides services to the user thread. Its life depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread automatically.
A daemon thread is a thread, which does not prevent the JVM from exiting when the program finishes but the thread is still running.
Main difference between daemon thread and user thread is that as soon as all user thread finish execution java program or JVM terminates itself, JVM doesn't wait for daemon thread to finish there execution. As soon as last non daemon thread finished JVM terminates no matter how many Daemon thread exists or running inside JVM.
There are many Daemon threads are running automatically, example: Garbage collector,...

Points to remember for Daemon Thread in Java
  • It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads.
  • Its life depends on user threads.
  • It is a low priority thread. 
  • Thread.setDaemon(true) makes a Thread daemon but it can only be called before starting Thread in Java. (WE can not make thread as daemon thread if the thread is already started, otherwise it will throw IllegalThreadStateException if corresponding Thread is already started and running.)
Why JVM terminates Daemon Threads?
 Daemon Thread sole purpose is to serve user threads. If the user threads finishes their job, then there is no use of Daemon threads. So JVM terminates Daemon threads. 

Daemon Thread methods in Thread class:

  1. isDaemon

    public final boolean isDaemon()
    Tests if this thread is a daemon thread.
    Returns:
    true if this thread is a daemon thread; false otherwise.
  2. setDaemon

    public final void setDaemon(boolean on)
    Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be invoked before the thread is started.
    Parameters:
    on - if true, marks this thread as a daemon thread
    Throws:
    IllegalThreadStateException - if this thread is alive
    SecurityException - if checkAccess() determines that the current thread cannot modify this thread

Example for Daemon Thread:




public class DaemonThreadExample {
  
    private static final class DaemonThreadTest implements Runnable {
        @Override
        public void run() {
            System.out.println("Daemon thread is running");
            try{
                while (true){
                    System.out.println(" Deamon thread is running.");
                }
            } catch(Exception e){
                //....
                System.out.println("Exception in ");
               
            } finally {
                System.out.println("Finally block from daemon thread.");
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("Starting main thread :" +Thread.currentThread().getName());
        Thread daemonThread = new Thread(new DaemonThreadTest(), "Daemon Thread");
        daemonThread.setDaemon(true);
        daemonThread.start();
        System.out.println("Main thread finishes.");
    }
} 

 

    In the above example, if you do not set "daemonThread.setDaemon(true)", the program will not exit even-though main-thread finishes, because that new "daemonThread" is not a daemon thread, it is a user thread, JVM will terminate when this daemon thread finishes. And if you set as a daemonThread.setDaemon(true), this daemon thread will terminates when the main-thread (user thread) finishes, and that time finally bock will not execute (because it terminates when JVM shutdown by user thread finishes).



No comments:

Post a Comment