JVM Shutdown Hook

JVM Shutdown Hook

Recently I got a problem where I had to perform some task while the application is shutting down. I worked with lot’s of problems where I have to write object unload tasks (finalize method). But this was something completely new to me.

After some googling I found that JAVA supports JVM shutdown hooks. These hooks are some threads that are executed when JVM is shutting down. Java’s Runtime class provide an addShutdownHook(Thread hook) method. This method will add this hook thread to be executed when all the tasks are done and JVM this about to shutdown/close.

public class JVMShutdownHook
{

    public static void main(String[] args)
    {
        System.out.println("Main start... ");
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            @Override
            public void run()
            {
                System.out.println("Finally shut down hook called");
            }
        });

        System.out.println("Main end....   ");
    }

}

Output

Main start... 
Main end....   
Finally shut down hook called

You can see from the output that code inside hook is executed at the end. This way you can handle events, free resources or something else like updating some flags/logs/process file when you application is shutting down. We often need these while running some jobs on server.


A moment’s insight is sometimes worth a life’s experience.
–Oliver Wendell Holmes (1809-1894)

Leave a Reply

Your email address will not be published. Required fields are marked *