Java Shutdown Hook sets the action when the JVM exits

We can set the operation to run when the JVM is ready to exit by calling the following method

 

java.lang.Runtime.addShutdownHook(Thread t)

 

Before the execution of the start method in the hook ends, the main thread and other sub-threads can still continue to perform their current tasks, so in a sense, this method provides the  opportunity to gracefully shutdown the server , such as polling the status of a process mark.

 

Test the following code to find out:

1. System.exit() can trigger Hook

2. Ctrl+C or Stop button in IDE can trigger Hook

3. Kill pid can trigger Hook

4. kill -9 pid will not trigger the hook

5.  Runtime.getRuntime().halt() does not trigger Hook

 

public static void main(String[] args) {

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("========working on shutdown signal received========");
            try {
                System.out.println("sleeping 2 seconds");
                Thread.sleep(2000);
                System.out.println("========really shutdown========");
            } catch (InterruptedException e) {
                e.printStackTrace ();
            }
        }
    }));

    int i = 0;

    while (true) {
        ++i;

        try {
            System.out.println("sleeping in main thread...");
            Thread.sleep(1000);

            if (i >= 10) {
                System.exit(0);
            }
        } catch (InterruptedException e) {
            e.printStackTrace ();
        }
    }
}

 

Other parts to note:

1. addShutdownHook() can be called multiple times to add multiple tasks

2. The execution order of multiple Hook tasks is unpredictable and multi-threaded execution

3. The task can be removed by Runtime.getRuntime().removeShutdownHook(hook)

4. If the Shutdown Hook task is already running, attempting to add or remove tasks will fail with IllegalStateException

5. The operation of adding and deleting tasks may be blocked by SecurityManager, RuntimePermission("shutdownHooks")

6. After the Shutdown Hook task starts running, it can still exit directly through the Runtime halt() method, and System exit() cannot exit directly

7. The normal shutdown operation will execute the Hook task, but any forced shutdown command may cause the Hook task not to be executed or not completed, and the internal error of the JVM will also cause the Hook task to not be executed or not completed.

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326462036&siteId=291194637