shutdown hook in java

Java shutdown hook is used to perform some operation when JVM is shutting down. It is mainly used to perform clean-up operations like closing log file etc. JVM shutdown when user presses ctrl+c on the command prompt or System.exit(0) method is called or user logoff or user shutdown etc.

The Runtime.getRuntime().addShutdownHook(Thread) method is used to register the thread with the Virtual Machine.


public class ShutdownHookTest {
  public static void main(String[] args) {
	  Runtime runtime=Runtime.getRuntime();  
	  runtime.addShutdownHook(new TestThread());  
	  System.out.println("Main sleeping.");  
	  System.out.println("Press ctrl+c to exit.");
	  try{Thread.sleep(2000);}catch (Exception e) {}  
class TestThread extends Thread{  
    public void run(){  
        System.out.println("Shut down hook job finished.");  


Main sleeping.
Press ctrl+c to exit.
Shut down hook job finished.
Content Protection by
Please Share