Java virtual machine shutdown hook (Shutdown hook)

Source click study Check

What is a Shutdown hook

Shutdown hook is a hook closed by Jvm. It is implemented by the Runtime#addShutdownHook(Thread hook) method. According to the api annotation, it can be seen that it is a series of thread objects that have been initialized but not yet executed. We can register a hook with Jvm to realize the function of closing resources and exiting smoothly when the program exits. The so-called graceful shutdown can also do the same.

How the Jvm shuts down

The program will call the hook function to do some finishing work only in the case of normal shutdown and abnormal shutdown. If it is forced to close, it will not be called. The forced shutdown directly terminates the jvm process without negotiation, and does not give the jvm a chance to breathe.

Notes on using shutdown hooks

  • A shutdown hook is essentially a thread (also called a Hook thread), and for multiple shutdown hooks registered in a JVM, they will be executed concurrently, so the JVM does not guarantee their execution order; due to concurrent execution, it is likely In order to avoid problems such as race conditions or deadlocks caused by improper code, it is strongly recommended to perform a series of operations in a hook.
  • The Hook thread will delay the shutdown time of the JVM, which requires that the execution time of the Hook thread must be reduced as much as possible in the process of writing the hook, so as to avoid time-consuming calculations in the hook thread, waiting for user I/O and other operations.
  • The execution process of the shutdown hook may be forcibly interrupted. For example, when the operating system is shut down, the operating system will wait for the process to stop, wait for a timeout, and the process has not stopped, and the operating system will forcibly kill the process. The hook is forced to abort during execution.
  • In the shutdown hook, the operations of registering and removing the hook cannot be performed. After the JVM has initialized the shutdown hook sequence, it is not allowed to add or remove the existing hook again, otherwise the JVM will throw an IllegalStateException.
  • System.exit() cannot be called in the hook, otherwise the shutdown process of the JVM will be stuck, but Runtime.halt() can be called.
  • Exceptions will also be thrown in hook threads. For uncaught exceptions, the thread's default exception handler handles the exception without affecting other hook threads and the normal exit of the JVM.

Simple example (see the source code for details)

1. Resources to be closed by the business

public class StudyResource implements AutoCloseable {

    public void close() throws Exception {
        System.out.println("Perform a project resource close operation");

2. Custom Hooks

 * @author: lixiaoshuang
 * @create: 2020-11-25 20:48
public class StudyShtudownHook extends Thread {

    private static final StudyShtudownHook INSTANCE = new StudyShtudownHook();
     * A collection of hooks that need to be closed, you can put all resource closing operations in the project here
    private final Set<AutoCloseable> autoCloseableHashSet = new HashSet<>();

    private StudyShtudownHook() {


    public static StudyShtudownHook getInstance() {
        return INSTANCE;

    public void registerAutoCloseable(final AutoCloseable autoCloseable) {

    public void run() {

    private void closeAll() {
        for (AutoCloseable autoCloseable : autoCloseableHashSet) {
  1. register hook with jvm
public class JvmHookDemo {

    public static void main(String[] args) throws InterruptedException {
        //self-implemented hook
        StudyShtudownHook instance = StudyShtudownHook.getInstance();
        //Put the resources that need to be closed into the hook
        StudyResource studyResource = new StudyResource();

        //register hook with jvm

        System.out.println("Execute business logic. . . .");
        System.out.println("The business logic is processed. . . .");

Output after executing this code:

Execute business logic. . . .

The business logic is processed. . . .

Perform a project resource close operation

Tags: Java jvm Back-end

Posted by sprinkles on Thu, 05 May 2022 19:47:21 +0300