2018-11-02

What is addShutdownHook method in java?


  • addShutdownHook method registers a new virtual-machine shutdown hook.
  • A shutdown hook is a initialized but unstarted thread. 
  • When JVM starts its shutdown it will start all registered shutdown hooks in some unspecified order and let them run concurrently. 


When JVM (Java virtual machine)  shuts down >
When the last non-daemon thread finishes, or when the System.exit is called.

Once JVM’s shutdown has begun new shutdown hook cannot be registered neither  previously-registered hook can be de-registered. Any attempt made to do any of these operations causes an IllegalStateException.

Example:

public class AddShutDownHookTest extends Thread{
   public static void main(String[] args) throws InterruptedException {   
          System.out.println("main thread started");
         
          Runtime.getRuntime().addShutdownHook(new Thread(){
       public void run() {
          try{
                System.out.println("executing shutdown hook");
          }catch (Exception e){
                e.printStackTrace();
          }
          System.out.println("shutdown hook executed successfully");
       }
     });
         
          Thread.sleep(4000); //Optional delay
          System.out.println("main thread ended");
   }
}
/*OUTPUT
main thread started
main thread ended
executing shutdown hook
shutdown hook executed successfully
*/

No comments:

Post a Comment