Shutdown Hook in Java

Shutdown hook allows performing some processing just before the java virtual machine shuts down. Shutdown hook is a simple thread which is registered with the JVM as a shutdown hook using the addShutdownHook  method of the java.lang.Runtime class.

public void addShutdownHook(Thread hook)

When the virtual machine starts its shutdown sequence, it starts all registered shutdown hooks. The order of execution of these threads is not fixed as they run concurrently.

The java documentation of the addShutdownHook method has very good explanation of shutdown hook. Here are some of the important facts about shutdown hook:

  • Once the shutdown sequence has begun one cannot register a new shutdown hook or de-register an existing one.
  • Virtual machine allows very small time for the processing of shutdown hooks so they should be written such that they complete their task quickly.
  • They should be written to be thread safe in order to avoid the chances of deadlock.
  • In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly.


The ShutdownHookDemo class is a simple example of using a shutdown hook. It registers two threads as shutdown hook and terminates the program by calling System.exit(0).

package com.technicalmusings.samples.runtime;

public class ShutdownHookDemo {

	public static void main(String... args) throws Exception{

		ShutDownHook hook = new ShutDownHook();
		Runtime runtime = Runtime.getRuntime(); 

                //adding the first shutdown hook

                //A quicker way to add a shutdown hook using an inner class
		runtime.addShutdownHook(new Thread() {
		    public void run() {
                          System.out.println("Second shutdown hook called.");
                //Terminate the VM to call the shutdown hook
* A Thread to be used as a Shutdown Hook
class ShutDownHook extends Thread {
	public void run() {
		System.out.println("First shutdown hook called.");


Second shutdown hook called.
First shutdown hook called.

Enjoy Learning,


About these ads

One thought on “Shutdown Hook in Java

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s