Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to make applications stop gracefully by ShutdownHook

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

Today, I will talk to you about how ShutdownHook makes the application stop elegantly. Many people may not know much about it. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

For applications, when stopped, the environment and data are generally restored to the way they were before running, which is similar to what tearDown does when unit testing. In order to restore the scene when it stops, there is a specific description in English:

Shutdown gracefully

In Java, in order to implement gracefully shutdown, there is a specific interface available, which is what we are going to talk about today, shutdown hook. It is similar to the callback function and is described in the document as follows:

The shutdown hook is just a thread that has been initialized but has not been started. When the virtual machine starts to enable its shutdown sequence, it starts all registered shutdown hooks in some unspecified order and makes them run at the same time. After running all the hooks, if exit termination is enabled, the virtual machine then runs all uncalled termination methods. Finally, the virtual opportunity is paused. Note that the daemon thread continues to run during the shutdown sequence, and the non-daemon thread continues to run if the shutdown sequence is initiated by calling the exit method.

To add shutdownHook to an application, all you need to do is do the following:

Runtime.getRuntime () .addShutdownHook (new Thread () {

Public void run () {/ * my shutdown code here * /}})

The run method of the Thread passed to the addShutdownHook method is the custom shutdown time cleanup logic.

Inside JDK, all added ShutdownHook is saved through a Map, which is executed when triggered.

Public void addShutdownHook (Thread hook) {

SecurityManager sm = System.getSecurityManager ()

If (sm! = null) {

Sm.checkPermission (new RuntimePermission ("shutdownHooks"))

}

ApplicationShutdownHooks.add (hook)

Static synchronized void add (Thread hook) {

Hooks.put (hook, hook)

}

Private static IdentityHashMap hooks;hooks = new IdentityHashMap ()

When does this shutdownHook usually be called?

As described in the JDK documentation, the Java virtual machine exits for two types of events:

The Java virtual machine shuts down in response to two types of events:

The program exits normally, which occurs when the last non-daemon thread exits, or when the exit (equivalent to System.exit) method is called. Or

Terminate the virtual machine in response to a user interruption, such as typing ^ C, or a system event occurs, such as user logout or system shutdown.

When the Java virtual machine exits, the shutdownHook for these settings is called in parallel. However, it should be noted that for abnormal ways to exit the Java virtual machine, such as killing processes, system power outages, etc., shutdownHook will not be executed.

Let's take a look at how ShutdownHook is used within Tomcat.

Inside the Catalina class, after each component in the server has been started, there is a piece of code like this

/ / Register shutdown hook

If (useShutdownHook) {

If (shutdownHook = = null) {

ShutdownHook = new CatalinaShutdownHook ()

}

Runtime.getRuntime () .addShutdownHook (shutdownHook);}

As we saw at the beginning of this article, he signed up for a ShutdownHook. This hook is as follows:

/ * *

* Shutdown hook which will perform a clean shutdown of Catalina if needed.

, /

Protected class CatalinaShutdownHook extends Thread {

Public void run () {

Try {

If (getServer ()! = null) {

Catalina.this.stop ()

}

} catch (Throwable ex) {

} finally {

}

}

}

Look, it is in shutdown by calling the stop method of the application server to shutdown gracefully.

In general, we stop Tomcat by calling the shutdown script, which essentially executes the stop method of the application server to stop, rather than being reversed by shutdownHook.

Therefore, when you read the source code, you will find something like this in the code:

/ * *

* Stop an existing server instance.

, /

Public void stop () {

Try {

/ / Remove the ShutdownHook first so that server.stop ()

/ / doesn't get invoked twice

If (useShutdownHook) {

Runtime.getRuntime () removeShutdownHook (shutdownHook)

} catch (Throwable t) {

ExceptionUtils.handleThrowable (t);}

We see that when we stop Server, we first execute the removeShutdownHook operation, which is clearly written in the comments to prevent server and stop from being executed twice.

Under which circumstances will it be executed twice?

When you stop Server using catalina's shutdown script, this method is not called from shutdownHook. At this point, shutdownHook has not been executed, so when JVM exits, shutdownHook will be triggered. If the remove has not been dropped here, it will be called again. We need to learn from this when we develop our own applications.

Seeing this, I hope you don't say that you are unexpectedly egg-bearing.

Of course, if you have blurted it out, then.

I found an example to prove that you have unwittingly used shutdownHook, for example, when you output the log, the following code is part of JDK's LogManager, we see that its construction method will directly add a shutdownHook named Cleaner.

Private LogManager (Void checked) {

/ / Add a shutdown hook to close the global handlers.

Try {

Runtime.getRuntime () .addShutdownHook (new Cleaner ()

} catch (IllegalStateException e) {

/ / If the VM is already shutting down

/ / We do not need to register shutdownHook.

}

}

Public void run () {

/ / This is to ensure the LogManager. Is completed

/ / before synchronized block. Otherwise deadlocks are possible.

LogManager mgr = manager

/ / Do a reset to close all active handlers.

Reset ()

}

When we add shutdownHook ourselves, we need to pay attention to the following:

Do not write time-consuming operations internally, nor do you write operations that can easily cause deadlocks. If there is a deadlock due to resource competition among multiple ShutdownHook, the application cannot be stopped. After reading the above, do you have any further understanding of how ShutdownHook makes the application stop elegantly? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report