articles

Home / DeveloperSection / Articles / Shutdown Hook in Java

Shutdown Hook in Java

Anupam Mishra4913 10-Dec-2015

 The shutdown hook is used to perform cleanup resources or saving state i.e. sending some alerts ,closing log files ,close the connections or something else before JVM goes shutdown as normally or abortly. If you want to execute some code before JVM shuts down, use shutdown hook. 

The following cases JVM shuts down when:


  • User presses Alt+F4 or ctrl+c on the command prompt.
  • System.exit(0) method is invoked
  • User logoff
  • User shutdown etc. 
So we have firstly override the method 

 public void addShutdownHook(Runnable r){} of my java program.

The addShutdownHook() method of Runtime class is used to registering  the

thread with the Virtual Machine i.e. JVM.

The object of Runtime class can be obtained by calling the static factory method getRuntime(). Runtime r = Runtime.getRuntime();

The method that returns the instance of a class is known as factory method.

The shutdown sequence can be stopped by invoking the halt (int) method of Runtime class.

For example, we have created MyThread class and override run method .When we invoked to another class that is using Shutdown Hook to given MyThread class object.

class MyThread extends Thread{ 
    public void run(){
System.out.println("shut down hook task completed..");
    }
}
public class ShutdownEx{
public static void main(String[] args)throws Exception
{
Runtime r=Runtime.getRuntime();
r.addShutdownHook(new MyThread()); //add thread to Shutdown Hook
System.out.println("Now I am sleeping... press ctrl+c to exit");
//r.halt(5000);
try{Thread.sleep(5000);}catch (Exception e) {}
}

/// In output JVM waits 5 second of the finishing this program 

Shutdown Hook in Java


Updated 07-Sep-2019

Leave Comment

Comments

Liked By