English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JVM Shutdown Hooks in Java

Thisjava.lang.Runtime.addShutdownHook (hook)The method registers a new virtual machine to close the hook. The Java virtual machine responds to two events for shutdown.

  • When the last non-daemon thread exits, or the exit method (equivalent to System.exit) is called, the program will exit normally, or

  • Terminate the virtual machine in response to user interruption (such as pressing ^C) or system-wide events (such as user logout or system shutdown).

The shutdown hook is just an initialized but not yet started thread. When the virtual machine begins its shutdown sequence, it will start all registered shutdown hooks in an unspecified order and run them concurrently. After all hooks are completed, if the exit when finalizing is enabled, it will run all uninvoked finalizers. Finally, the virtual machine will stop. Note that if shutdown is initiated by calling the exit method, daemon threads will continue to run during the shutdown sequence, and non-daemon threads will also continue to run.

declare

The following isjava.lang.Runtime.addShutdownHook()method declaration

public void addShutdownHook(Thread hook)

Parameter

Hook-A Thread object that is initialized but not yet started.

Return value

This method does not return a value.

Exception

  • IllegalArgumentException-If the specified hook has already been registered, or it can be determined that the hook is already running or has already started running.

  • IllegalStateException-If the virtual machine is already in the process of shutting down.

  • SecurityException-If there is a security manager and it denies RuntimePermission(" shutdownHooks").

Example

The following example demonstrates the usage of the lang.Runtime.addShutdownHook() method.

package com.w3codebox;
public class RuntimeDemo {
   //The class that extends the thread to be called when the program exits
   static class Message extends Thread {
      public void run() {
         System.out.println("Bye.");
      }
   }
   public static void main(String[] args) {
      try {
         //Register the message as a shutdown hook
         Runtime.getRuntime().addShutdownHook(new Message());
         //Print program status
         System.out.println("Program is starting...");
         //Make the thread sleep3seconds
         System.out.println("Waiting for 3 seconds...");
         Thread.sleep(3000);
         //Print program is closing
         System.out.println("Program is closing...");
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Let's compile and run the above program, which will produce the following results.

Output result

Program is starting...
Waiting for 3 seconds...
Program is closing...
Bye.