JVM Shutdown Hook

22/01/2012

Java JVM provides you a hook to register a thread with the shutdown initiation sequence. Once a thread is registered, on every shutdown that thread is run.

JVM’s shutdown sequence has two phases.

  1. All registered shutdown hooks are started in some unspecified order and allowed to run concurrently until they finish.
  2. All un-invoked finalizers are run if finalization-on-exit has been enabled.

After the above two phases are complete, java virtual machine halts.

Its not a complicated exercise, but a less known feature of java. You might require this to release critical resources in the event of unexpected JVM shutdown. You use finally in a try block to release resources and that is completely different.

Just a single line of code will register with the hook of JVM shutdown. You use, Runtime class to register the thread.

System.getRuntime().addShutdownHook(<thread instance>);
  • If you register multiple threads with shutdown hook, all those threads will be run in parallel on shutdown. If you wish to run them in a sequence, then you need to have only one thread registered and have your custom logic controlled within that.
  • If you are shutting down the VM using Runtime.getRuntime().halt, this will not invoke the shutdown hook. It will abruptly shutdown all running process and close the show.

Example Code for JVM Shutdown Hook

public class JVMShutdownHookTest {
  public static void main(String[] args) {
    JVMShutdownHook jvmShutdownHook = new JVMShutdownHook();
    Runtime.getRuntime().addShutdownHook(jvmShutdownHook);
    System.out.println("JVM Shutdown Hook Registered.");
    System.out.println("Pre exit.");
    System.exit(0);
    System.out.println("Post exit.");
  }

  private static class JVMShutdownHook extends Thread {
    public void run() {
      System.out.println("JVM Shutdown Hook: Thread initiated.");
    }
  }
}

Output:
JVM Shutdown Hook Registered.
Pre exit.
JVM Shutdown Hook: Thread initiated.

In the above program, I manualy call the System.exit() and make the JVM to shutdown. Once the System.exit is invoked the phase I of shutdown sequence is initiated and that starts then registered thread ‘jvmShutdownHook’ and then halts the JVM.

Runtime.runFinalizersOnExit() method is almost similar to addShutdownHook() but its depreciated in 1.2

In case if you are wondering on how to detect the web context shutdown in application server scenarios, you can use ServletContextListner

When shutdown hook will NOT be initiated

There is no guarantee that always the shutdown hooks will run. There might be a devastating crash of the whole system and JVM might crash due to it. In similar circumstances there is no guarantee that shut down hooks will invoke the thread. Similarly if native OS kills the JVM process then this shutdown hook sequence will not be initiated. Therefore in all cases when the JVM is shutdown abnormally the hook will not be initiated.

Note:

  • You cannot register a shutdown hook after a shutdown is intiated. That is, if you try to register a thread to shutdown hook from within another thread that is already registered with the hook you will get IllegalStateException.
  • You can use Runtime.getRuntime().halt(status); to halt JVM abruptly after the shutdown sequence is initiated.

Very Helpful and Interesting.
thanks ..

Anonymous on January 23rd, 2012 12:25 pm

what is difference between System.exit(0);
and System.exit(1);

pradeep on January 23rd, 2012 12:34 pm

Is calling Runtime.getRuntime().halt(status), a safe behavior? This would kill other registered threads running in parallel. Correct me if am wrong.

Praveen on January 23rd, 2012 1:02 pm

Really Interesting. Got some new Knowledge about something new in Java.

Dev Ghotkule on January 23rd, 2012 3:15 pm

Thanks for the nice and interesting topic.

Can you provide some real time examples where it can be helpful?

Rajesh on January 23rd, 2012 3:24 pm

I didn’t understand the meaning of “hook” here.and without understanding the proper mean you use this word,this post is meaningless.please don’t mind and reply.

utkal on January 23rd, 2012 3:45 pm

please write something more on this topic like where is the exact use of this,any adv.

utkal on January 23rd, 2012 4:11 pm

Sir i could not understand about JVM Shutdown. Is it means that Jvm will not work when we apply this code…….??????Please reply me……..

Arjun Sah on January 24th, 2012 1:45 pm

Thanks! Easy to read and informative. I like the stoplight graphics, too.

Rick

Rick on January 25th, 2012 6:03 am

@Pradeep

Simply look at the javadocs and you can easily see answer to your question…Anyhow here is a snippet..

” By convention, a nonzero status code indicates abnormal termination.”

So in short System.exit(0) and System.exit(1) will both shutdown the JVM. Non-zero code by convention is used if there is an abnormal shutdown. In the context of this particular post we will use 0 since the shutdown is a well thought shutdown.

Rajwinder Singh on January 25th, 2012 9:26 pm

fsdf

sfa on January 26th, 2012 9:32 pm

Mr. Utkal,
whoever you are, hook is “A piece of metal or other material, curved or bent back at an angle, for catching hold of or hanging things on.”
don’t wate your time on Java website when you want to be an english professor. its not for you.

Anonymous on January 27th, 2012 7:49 am

Good one,,,,
can you post info about Java Class Loaders and Custom class loaders in Java .

PaddyREC on January 27th, 2012 10:28 am

The basics of Java class loaders: Very old post but Nice…
http://www.javaworld.com/javaworld/jw-10-1996/jw-10-indepth.html?page=1

Anonymous on January 27th, 2012 10:24 pm

nice and useful.

Suyog on January 28th, 2012 3:10 am

Hi Joe,

You should add captcha for posting comments. This portion is easy to automate and break your website.

Really cool site. Keep it up.

Suyog on January 28th, 2012 3:15 am

Can shutdown hook be added for scheduled shutdown’s aswell?

Java Learner on February 8th, 2012 3:05 pm

@Java Learner
Definitely a shutdown hook can be added for scheduled shutdown as the process of attaching a shutdown hook (which is a thread here) has nothing to do with whether it is a scheduled/unscheduled shutdown. In fact, as Joe has rightly pointed out, in case of unscheduled shutdown, the JVM may not guarantee to invoke the shutdown hook. So a shutdown hook is more useful for a scheduled shutdown of JVM.

Ajit on February 22nd, 2012 1:16 pm


Email:

about
I am Joe, author of this blog. I run this with loads of passion. If you are into java, you may find lot of interesting things around ...more about me. Google+
java badge
Home