Thursday, 27 December 2012

Daemon Thread - Java

The major difference between normal thread and daemon thread is that JVM always waits for normal thread to finish, but JVM will never wait for daemon thread to terminate. Means ones normal threads in program are finishing execution the JVM will terminate without caring how many daemon threads are executing.
Here I am giving one simple example proving above mechanism,


class Main implements Runnable
{
    Thread normal, daemon;
    public static void main(String args[])
    {
        Main m = new Main();
        m.checkOut();
    }
   
    public void checkOut()
    {
        try
        {
            normal = new Thread(this);
           
            daemon = new Thread(this);
            daemon.setDaemon(true);
           
            normal.start();
            daemon.start();
        }
        catch(Exception e)
        {
            System.out.print("\nException : " + e);
        }
    }
   
    public void run()
    {
        try
        {
            synchronized (this) {
                System.out.print("\nThis is thread : " + 1);
                Thread.sleep(2000);
                System.out.print("\nThis is thread : " + 2);
                Thread.sleep(2000);
                System.out.print("\nThis is thread : " + 3);
                Thread.sleep(2000);
                System.out.print("\nThis is thread : " + 4);
            }
        }
        catch(Exception e)
        {
            System.out.print("\nException : " + e);
        }
    }
}


In output you can see that as soon as normal thread is finishing execution the JVM is exiting without waiting for daemon thread to complete.

In java by default thread is not daemon thread. We can use "setDaemon()" method to make our normal thread daemon. Here we have to remember that setDaemon() method must be called before call to start() method otherwise it will throw an exception IllegalThreadStateException.


Generally we can use this daemon thread for background processing purpose. Marking thread as daemon means it will be killed safely when JVM will exit. Practically we can use this daemon thread for background timers, keeping watch on something throughout our program execution etc.

Apart from this behavior daemon thread works similar to normal thread. We can use all normal thread methods with daemon thread.

No comments:

Post a Comment