Runtime.addShutdownHook()

SHARE & COMMENT :

Preface

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

also read:

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:
?
1
2
3
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.

 

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. Pankaj Lilhare says:

    Superb explanation.. Thank you so much..

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better