JVM Shutdown Hook - addShutdownHook in Java

JVM Provides hook to register thread with shutdown init sequence. Meaning whenever shutdown will happen, this thread will run.You may require this to cleanup resources in case of unexpected JVM Shutdown.

Runtime.class provides method addShutdownHook whereYou can provide Thread instance.
public void addShutdownHook(Thread hook)

  • If multiple threads are registered as part of ShutdownHook, all registered threads will be run in parallel. 
  • If You are shutting down Virtual Machine using Runtime.getRunTime().halt then It will not invoke shutdownhook and will shutdown all running process quickly.

package com.anuj.threading;
/**
 * ShowDown Hook 
 * used to perform clean up resources when JVM shutDown normally or abnormally 
 * @author Anuj
 *
 */
class ShutDownHookExample extends Thread{

 @Override
 public void run() {
  System.out.println("JVM Shutdown Hook : Thread running");
 }
 
 /**
  * @param args
  */
 public static void main(String[] args) {

  Runtime runtime = Runtime.getRuntime();
  runtime.addShutdownHook(new ShutDownHookExample());  
  
  System.out.println("shutDownHook registered");
  System.out.println("Before Shutdown");
  System.exit(0);  
 }

}

Output :
shutDownHook registered
Before Shutdown
JVM Shutdown Hook : Thread running

No comments:

Post a Comment