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 realize safe exit by JVM

2025-04-01 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 to achieve safe exit of JVM. Many people may not know much about it. In order to let everyone know more, Xiaobian summarized the following contents for everyone. I hope everyone can gain something according to this article.

background

Go online! Restart! Are you still upset about missing missions? Look here, look here, no longer lose tasks, JVM can safely exit

In the transaction process, in order to improve the performance of the service, we have done some asynchronous optimization, such as updating the user's most recently used receiving address, sending various notification messages through MQ after the bill of lading is completed, cleaning up the user's shopping cart, etc. These operations speed up the response speed of the application and also bring a hidden danger. How to ensure the execution of asynchronous operations? This scenario occurs primarily at application restart time, and for asynchronous operations via threads or thread pools, asynchronous operations performed in the background may not have completed at JVM restart time. In this case, the JVM security shutdown is required to ensure that the asynchronous operation is completed before the JVM executes the shutdown.

More generally, many applications on Linux use kill -9 pid to forcibly kill processes, which is simple and efficient, so many application stop scripts often choose to use kill -9 pid. Forcing a process to exit has some side effects, which are equivalent to a sudden power loss for the application, and may cause the following problems:

Data in cache has not been persisted to disk, resulting in data loss;

The file is in write operation, and the update is not completed. Suddenly exit, resulting in file corruption;

There are still received tasks in the task queue of the thread pool that have not been processed in time, resulting in task loss;

The database operation has been completed, for example, when the account balance is updated and the response message is ready to be returned to the client, the message is still queued in the sending queue of the communication thread waiting to be sent, the process is forced to exit, resulting in the response message not being returned to the client, and the client initiates a timeout retry, which will bring about repeated updates;

Other issues such as...

To avoid these problems, which have the potential to impact our business and cause unnecessary damage, we need to do some cleanup work when the JVM is shut down, and the JVM provides shutdown hooks to do these things. This article explores the use of close hooks.

JVM shutdown

First, let's look at what causes JVM shutdown.

For several cases of forced shutdown, the system shuts down, the operating system will notify the JVM process to shut down and wait, once the wait timeout, the system will forcibly suspend the JVM process;kill-9, Runtime. halt (), power failure, system crash These methods will directly suspend the JVM process without discussion, and the JVM has no chance to perform the tail work. Therefore, for applications, we strongly do not recommend using kill -9 as a brute force exit.

For several cases of normal shutdown and abnormal shutdown, before the JVM shuts down, it will call the registered shutdown hooks. Based on this mechanism, we can put the work of cleaning the tail in the shutdown hooks, and then make our application exit safely. For platform commonality, we recommend that applications exit the JVM using System.exit(0).

The interaction process between JVM and shutdown hooks is shown below. You can further learn how shutdown hooks work against the source code.

Jvm Safe Exit

For tomcat Web applications, we can register custom hooks directly through Runtime.addShutdownHook(Thread hook) to clean up resources in the hooks; for worker applications, we can safely exit the application in the following way.

Signal-based Process Notification Mechanism

Signals are an analog of the interrupt mechanism at the software level. In principle, a process receiving a signal is the same as a processor receiving an interrupt request. In layman's terms, a signal is an asynchronous communication mechanism between processes. Signals are platform-dependent, and some of the terminating process signals supported by Linux platforms are as follows:

Windows platform has some differences, some of its signal examples are as follows:

Signal selection: In order not to interfere with the normal operation of the signal, but also to simulate Java asynchronous notification, on Linux we need to select a special signal. By looking at the description on the signal list, SIGUSR1 and SIGUSR2 are signals that allow user customization, we can select SIGUSR2, and on Windows we can select SIGINT.

Through this signaling mechanism, a specific signal is sent to the application JVM, which can sense and process the signal, and thus can accept the program exit instruction.

Safe Exit Implementation

Let's first look at the general JVM safe exit flowchart:

The first step is to initialize the Signal instance when the application process starts. Its code example is as follows:

The parameter of Signal constructor is String character string, which is the semaphore name introduced above.

Step 2: Obtain the corresponding signal name according to the name of the operating system. The code is as follows:

If yes, select SIGINT to receive Ctrl+C interrupt command; otherwise, select USR2 signal to receive SIGUSR2 (equivalent to kill -12 pid) command.

The third step is to register the instantiated SignalHandler to the JVM Signal. Once the JVM process receives kill -12 or Ctrl+C, it will call back the handle interface. The code example is as follows:

ShutdownHandler implements the handle(Signal sgin) method of SignalHandler interface. The code example is as follows:

Step 4: Initialize the ShutdownHook thread of JVM in the handle interface that receives the signal callback and register it in Runtime. The example code is as follows:

Step 5, after receiving the process exit signal, execute the virtual machine exit operation in the callback handle interface. The example code is as follows:

When the JVM exits, the underlying layer will automatically detect whether the user has registered the ShutdownHook task. If so, the Run method of the registered hook will be automatically executed. The application only needs to perform the finishing work in ShutdownHook. The example code is as follows:

Through the above several steps, we can easily achieve safe exit of JVM, in addition, usually safe exit needs to have a timeout control mechanism, such as 30S, if the timeout time is still not completed exit, then the shutdown script directly calls kill -9 forced exit.

Notes on using close hooks

A close hook is essentially a thread (also known as a Hook thread). For multiple close hooks registered in a JVM, they will execute concurrently, so the JVM does not guarantee their execution order; since they execute concurrently, it is likely that improper code will cause race conditions or deadlocks. To avoid this problem, it is strongly recommended to perform a series of operations in a hook.

Hook threads delay JVM shutdown time, which requires that Hook thread execution time must be reduced as much as possible in the process of writing hooks to avoid time-consuming calculations, waiting for user I/O, and so on.

Close hook execution may be forcibly interrupted, such as when the operating system shuts down, the operating system will wait for the process to stop, wait for a timeout, the process has not stopped, the operating system will force the process to kill, in such cases, close hook execution is forcibly aborted.

In closing hooks, you cannot register or remove hooks. After the JVM initializes the closing hook sequence, you are not allowed to add or remove existing hooks again, otherwise the JVM throws IllegalStateException.

System.exit() cannot be called on the hook, otherwise the JVM shutdown process gets stuck, but Runtime.halt() can be called.

Hook threads also throw exceptions. For uncaught exceptions, the default exception handler of the thread handles the exception without affecting other hook threads and the normal exit of the JVM.

In order to ensure the execution of asynchronous operations during application restart and avoid various problems that may arise from forced exit of JVM, we can actively notify JVM to exit by closing hooks and custom signals, and perform some cleaning work of the application before the JVM is closed to further ensure that the application can exit safely.

After reading the above, do you have any further understanding of how the JVM implements safe exit? If you still want to know more knowledge or related content, please pay attention to 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