Runtime.addShutdownHook()

Preface:
Every Java Program can attach a shutdown hook to JVM, i.e. piece of instructions that JVM should execute before going down.

Problem:
A program may require to execute some pieces of instructions when application goes down. An application may go down because of several reasons:
  • Because all of its threads have completed execution
  • Because of call to System.exit()
  • Because user hit CNTRL-C
  • System level shutdown or User Log-Off
Few scenarios where this requirement fits are:
  • Saving application state, e.g. when you exits from most of the IDEs, they remember the last view
  • Closing some database connections
  • Send a message to System Administrator that application is shutting down.
Solution:
Shutdown Hook comes to rescue in all such scenarios. Application attach a shutdown hook to thereself, that JVM runs when application goes down.

Concept at Abstract level:
Write all the instructions(java code) in a thread's run method and call java.lang.Runtime.addShutdownHook(Thread t). This method will then register this thread with JVM's shutdown hook. At the time of shutting down, JVM will run these hooks in parallel (Thread will be started only at the time of shut down by JVM itself).

Sample code:
public class AddShutdownHookSample {
 public void attachShutDownHook(){
  Runtime.getRuntime().addShutdownHook(new Thread() {
   @Override
   public void run() {
    System.out.println("Inside Add Shutdown Hook");
   }
  });
  System.out.println("Shut Down Hook Attached.");
 }
public static void main(String[] args) {
  AddShutdownHookSample sample = new AddShutdownHookSample();
  sample.attachShutDownHook();
  System.out.println("Last instruction of Program....");
  System.exit(0);
 }}

Output is:
Shut Down Hook Attached.
Last instruction of Program....
Inside Add Shutdown Hook
I think now I am clear with on how to use addShutDownHook. One can attach as many shutdown hooks as he wants, but beware, these hooks will be run in parallel, so keep concurrency in mind, so that no deadlock or race condition exists.

Are you going to implement it in your application:
There are few more things that should be kept in mind while using this method:
  • Number of Shutdown hooks: There is no limitations on number of shutdown hooks, one can attach as many shutdown hooks as he wants. See the modified version of run method above,
    public void attachShutDownHook(){  
      for(int i =0; i<10;i++){
       Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {    
         System.out.println("Inside Add Shutdown Hook : " + Thread.currentThread().getName()) ;
        }
       }); 
      }

    See, we have attached ten shutdown hooks here.
  • When to attach Shutdown hook: Anytime!!! One can attach a shutdown hook at any instance of time, but before JVM starts shutting down. If one tries to register a shutdown hook after JVM starts shutting down, then it will throw an IllegalStateException with message, "Shutdown in progress" 
  • Attaching same hook again: One can't attach same hook again and if it happens, it will throw  IllegalArgumentException with message "Hook previously registered
  • De-Register a Hook: One can de-register a hook as well by simply calling method Runtime.removeShutdownHook(Thread hook)
    PS: Most of the time, shutdown hooks are registered using anonymous inner classes, but since we don't have any reference available for them, we should not use anonymous inner classes for hooks that we may de-register, because we need to pass there reference in removeShutdownHook(Thread hook) method.
  • Keep an eye on Concurrency: In case one have attached more than one shutdown hook, then they will run in parallel and hence pron to all issues related to threads, e.g. deadlocks or race conditions. Java Doc for the method also state that:
    /**
      * A <i>shutdown hook</i> is simply an initialized but unstarted thread.
      * When the virtual machine begins its shutdown sequence it will start all
      * registered shutdown hooks in some unspecified order and let them run
      * concurrently. When all the hooks have finished it will then run all
      * uninvoked finalizers if finalization-on-exit has been enabled. Finally,
      * the virtual machine will halt. Note that daemon threads will continue to
      * run during the shutdown sequence, as will non-daemon threads if shutdown
      * was initiated by invoking the <tt>{@link #exit exit}</tt> method.
      */

  • Reliability of Shutdown Hook: JVM tries his best to execute shutdown hooks at the time of going down, but it can't be guranteed, e.g. when JVM is killed using -kill command on Linux or Terminate Process on windows, then JVM exits instantly or it crashes because of some native code invocation.
  • Keep an eye on Time Consumption by hooks: One of the important thing to note is that shutdown hooks should not be time consuming. Consider the scenario when user logs off from OS, then OS assign very limited time to gracefully shutdown, hence in such scenarios JVM can forcefully exit.

    Conclusion:
    Runtime.addShutdownHook(Thread hook) can be a very handy tool, especially in big applications like server implementations as it provide a generic mechanism for graceful exit from JVM. Still, it should be used with care.

    References: 

    19 comments:

    MichaƂ Karolik said...

    Helpful feature, thank you for sharing : )

    Vineet Mangal said...

    @Michal: You are welcome!!

    Ashish said...

    Nice Post !

    One Gotcha to watch for... the sequence of shutdown hook execution cannot be predicted.. so ensure there in no dependency among shutdown hooks side effect, along side concurrency.

    Vineet Mangal said...

    @Ashish: Nice to see that you like the post, Thanks.
    I think when I write that shutdown hooks are threads and these will run in parallel, it means that all thread related concepts need to be taken care!!!

    Anonymous said...

    Nice, new thing, written in simple and easy to understand.
    Deep

    Vineet Mangal said...

    @Deep: Thanks!!!

    Anonymous said...

    Thanks for your job

    MG

    Aasif Ali said...

    i am really impressed by the post...it is easiest way to learn shutdownhook...

    Anonymous said...

    what will happened in case of Java crash or hardware failure

    Unknown said...

    Nice post.For similar post refer this link Shutdown Hooks

    latif mohammad khan said...

    Thank you for Good Explanation

    Unknown said...

    great method and nice explanation !

    Anonymous said...

    I have attached shutdown hook in my code static method. But when I stop windows process (which is java), it is not calling this shutdown hook.

    Can you give any hint what could be the reason behind it?

    Anonymous said...

    Thanks, very nice explanation.

    Sharif said...

    Great! thanks for sharing.

    santosh srinivas said...

    Super. Thank you sharing and explaining.

    Unknown said...

    Helpful, thanks for sharing!

    Unknown said...

    Very helpful, thanks a lot !!!

    GenTech said...

    Thanks for share very easy process to learn, i really like your post.

    Genesis Technologies having IT job in Indore for developers in Java, PHP, iOS, and android.
    We are looking for talented people who are willing to work in a challenging environment.