JVM shutdown hook in Java with example

Let’s see about the JVM shutdown hook in Java in this tutorial. The JVM, which stands for ‘Java Virtual Machine’ normally shutdowns if the program exits normally when last non-daemon thread exists. Also in case of a user interruption or a system-wide event such as user logging off from the system or system getting shutdown, JVM gets terminated.

java.lang.Runtime.addShutdownHook(Thread)

This method of Runtime class registers a new virtual-machine shutdown hook. This method has no return type and its argument type method which accepts thread hook as an argument. A shutdown hook is just an initialized but unbegun thread. This method gives permission to developer to insert a section of code to be executed while JVM is shutting down. Also, we can remove previously registered shutdown hook by using removeShutdownHook(Thread) method of Runtime class.

Declaration :

public void addShutdownHook(Thread)

Exception :

This method can throw the following Exceptions :

  • IllegalArgumentException : When the hook has been already registered.
  • IlleagalStateException : When the virtual machine is previously in the operation of shutting down.
  • SecurityException : When a security manager denies ShutdownHooks.

Example :

Let’s see an example to understand neatly about JVM shutdown hook in Java :

package java;

//This will be called when the program is exiting
class Helper extends Thread
{
 public void run()
 {
  System.out.println("Shutting down");
 }
}
public class JVM_Example
{
 public static void main(String[] args)
 { 
  //Registering Helper as an Shutdown hook
  Runtime.getRuntime().addShutdownHook(new Helper());

  System.out.println("Program started...");
  System.out.println("Program running...");
  System.out.println("Program ended...");
 }
}

The output of the program will be :

Program started...
Program running...
Program ended...
Shutting down.

In the above program, we are simply creating two classes. In which, ‘Helper’ class extends java.lang.Thread class. We are overriding run() method in it by writing our code that we want to execute while virtual machine is shutting down. Then in main class ‘JVM_Example’, we registered an instance of a ‘Helper’ class as a shutdown hook to the virtual machine by calling Runtime.getRuntime.addShudownHook(Thread) method.
We can clearly see in the output that shutdown hook is getting called by JVM after the execution of main method.

Leave a Reply