JVM Shutdown Hook

Last modified on November 30th, 2014 by Joe.

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();

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:

Comments on "JVM Shutdown Hook"

  1. pradeep says:

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

  2. Praveen says:

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

  3. Dev Ghotkule says:

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

  4. Rajesh says:

    Thanks for the nice and interesting topic.

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

  5. utkal says:

    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.

  6. Arjun Sah says:

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

  7. Rick says:

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

    Rick

  8. Rajwinder Singh says:

    @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.

  9. Anonymous says:

    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.

  10. PaddyREC says:

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

  11. Suyog says:

    nice and useful.

  12. Suyog says:

    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.

  13. Java Learner says:

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

  14. Ajit says:

    @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.

  15. cndhu says:

    Please explain coupling and cohesion

  16. Sabyasachi says:

    Nice one…Sir,

    Plz provide some lession on Comparator and Comparable interface.And with some real time example when to use.

  17. harish says:

    helped me in understanding shudown hooks thanks

  18. Kunal says:

    Hi.. I have been readiing your post on design patterns and other “Eye-Catching” topics. You have really written very well organized, very useful topics with very simple layman language.. I really appreciate this. Keep writting.

    Thanks
    Kunal

  19. Anonymous says:

    realy nice topic ,was unknown to this… thanks

  20. Rahul says:

    sir What is the difference between import in java and include in ‘c’

  21. abhiroop says:

    First time learned about security manager and Shutdown in jvm ….

  22. abhiroop says:

    While learning in more granular layer in
    Shutdown class I found a new ThreadDeath class . What’s importance of this class and why they made serialVersionUID hardcoded , where exactly its in use?

  23. Satish says:

    interesting articles ….

  24. uma mahesh yandamuri says:

    Excellent work
    This blog is very useful
    Thank you sooo much…

  25. sanjay says:

    hello, i want the write shutdown time in a .txt file in real time.
    below code doesn’t work ,,,
    =======================
    public void run()
    {
    long starttime = 0,shutdown=0;
    SimpleDateFormat ft = new SimpleDateFormat(“EEE, yyyy-MM-dd HH:mm:ss a”);
    String shut_down_time = ft.format(new Date());
    if(flag==true)
    {
    try
    {
    Date d=ft.parse(startup_time);
    Date dt=ft.parse(shut_down_time);
    starttime = d.getTime();
    shutdown = dt.getTime();

    }
    catch (ParseException ex)
    {
    System.err.println(“abnormal : “+ex.getMessage());
    }
    Date dNow = new Date();
    // log(“Flag true total Active time=”+m.millisecondsToString(shutdown – starttime));
    log(“Total idle time = 0 “);
    log(“============================================================================”);
    log(“Without Idle”);
    log(“\n”+”Online Grand Total : “+(shutdown – starttime)+” “+”\n”+”Idle Grand Total : “+total_idle_time+” “);
    log(“Total Active Time = “+m.millisecondsToString(shutdown – starttime)+” “+”\nTotal Inactive Time = “+m.millisecondsToString(total_idle_time)+” “+”\n”+ft.format(dNow) + ” =Shutdown time “);
    log(“=============================================================================”);
    // log(“\n”+”Online Grand Total : “+(shutdown – starttime)+” “+”\n”+”Idle Grand Total : “+total_idle_time+” “);
    log(“\nEND”);
    }

  26. venkata reddy mylarapu says:

    this code snippet with explanation was so helpful, like this forum.

    Thanks.:)

  27. SAM says:

    this is very good one…so i think that i need to implement this to my program to understand better.

    Thanks:

  28. basant says:

    sir how to save all the data in java application(desktop) if power is off or system is restarted automatically . please reply as soon as possible its urgent.

    Thanks in advance

  29. basant says:

    sir how to save all the data in java application(desktop) if power is off or system is restarted automatically . please reply as soon as possible its urgent.

    Thanks

  30. Anonymous says:

    Hi Joe,
    If we kill the java process using kill command in linux environment would these hooks be in effect.

  31. Joe says:

    No, the hooks may not work. It will be an abrupt shut down.

  32. Sam says:

    Hi Joe,

    I suggest adding some real life examples would greatly benefit readers. For example, taking a thread dump using shutdown hooks is only sane way to track down what caused the JVM crash

  33. Bharat Patel says:

    There is no difference at all… Both are exactly same. if you check the code of this method it has nothing to do with the argument you pass.

  34. Andy says:

    nicely written and useful, thanks

  35. Gautam says:

    Great piece of information. Thanks for putting it out so well.

  36. suganya says:

    Thanks for sharing your knowledge. Very simple and easy to understand.

Comments are closed for "JVM Shutdown Hook".