Archive

Posts Tagged ‘hook’

Java shutdown hooks

August 24th, 2009 4 comments

Java allows you to add shutdown hooks to your code. A shutdown hook is simply a thread that has been left in the initialized state. When your JVM is about to shutdown, the shutdown hook thread kicks in. The finalization processes of java objects run after the shutdown hooks complete. The JVM allows you to register more than one shutdown hook.

Let us take a look at how this is done

public class Task
{
    public static void main(String[] args)
    {
        Runtime runtime = Runtime.getRuntime();
        Thread thread = new Thread(new ShutDownListener());
        runtime.addShutdownHook(thread);
        someProcess();
    }
 
    private static void someProcess()
    {
        try
        {
            System.out.println("I am busy");
            Thread.sleep(2000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}
 
class ShutDownListener implements Runnable
{
    @Override
    public void run()
    {
        System.out.println("I am shutting down");
    }
}

The Task class is a simple class that runs a process. Once this process finishes up, we want the JVM to run a shutdown hook to notify us that the JVM is shutting down. When this program is run, the output is

I am busy
I am shutting down

Nice !

Lets experiment a little more. How robust is a shutdown hook ? After the someProcess() method is called let us analyze what will happen when one of the following statements are added

Categories: java Tags: ,