JVM Security exit (how to gracefully shut down the Java service)

Source: Internet
Author: User

Https://tech.imdada.cn/2017/06/18/jvm-safe-exit/?utm_source=tuicool&utm_medium=referral

background

User: The goods have arrived, the shopping cart how still has just bought the thing, what?
Products: Users reflect that the bill of lading has been completed, how did not clear the shopping cart, research and development to see if there is a bug ah.
Research and development: Well, let me see. @#¥%......&* () A wild check, search GA, at that time on the line, restart application, asynchronous task lost ...
Product: Can line, on-line you lose task, throw not disgrace ah.
R & d:............

Online, reboot! Are you still worried about losing your job? Look here, look here, never lose a task, the JVM can safely exit

In the transaction process, in order to improve the performance of the service, we do some asynchronous optimizations, such as updating the user's most recently used delivery address, the bill of lading after the completion of the implementation of MQ to send various notification class messages, cleaning up the user's shopping cart and so on these operations, asynchronous speed up the application response speed also brings a hidden danger, How to guarantee the execution of asynchronous operations. This scenario occurs primarily when a restart is applied, and the asynchronous operation performed in the background may not have been completed when the JVM is restarted for the asynchronous process through a thread or thread pool. The JVM then shuts down after the JVM is safely shut down to ensure that the asynchronous operation completes.
More broadly, many applications on Linux often use the kill-9 PID to force the process to kill, which is simple and efficient, so many application stop scripts usually choose the Kill-9 PID method. Forcing a process exit can have some side effects that, for the application, are equivalent to a sudden power loss, which can cause problems such as the fact that the data in the cache has not persisted to disk, causing data loss, and that the write operation for the file, no update completed, a sudden exit, resulting in file corruption; The task queue in the thread pool has not yet been processed, causes the task to be lost; The database operation has been completed, such as account balance Update, ready to return the reply message to the client, the message is still queued for sending in the communication thread's send queue, and the process force exit causes the reply message not to be returned to the client. The client initiates a timeout retry, which causes a recurring update problem, other problems, etc.

These problems can have an impact on our business, causing unnecessary losses, and to avoid these problems, we need to do some cleanup work when the JVM shuts down, and the JVM provides a close hook (shutdown hooks) to do these things. This paper explores the relevant content of using closed hooks. JVM shutdown

First, we know what will cause the JVM to shut down, as shown in the following figure

For several cases of forced shutdown, the system shuts down, the operating system notifies the JVM that the process shuts down and waits, and once the wait times out, the system forces the JVM process to abort; kill-9, Runtime.halt (), power outages, system crash these ways will directly terminate the JVM process without negotiation, The JVM has absolutely no chance of performing cleanup work. Therefore, for applications, we strongly do not recommend the use of kill-9 this violent way to exit.
In the case of a normal shutdown, an abnormal shutdown, the JVM will invoke the registered shutdown hooks before it shuts down, and based on this mechanism, we can put the cleanup work in the shutdown hooks, thus allowing our application to exit safely. Based on platform versatility, we recommend that applications exit the JVM using System.exit (0).

The JVM and shutdown hooks Interactive process as shown in the following diagram, you can control the source of further learning shutdown hooks working principle.
JVM Security Exit

For Tomcat Web applications, we can register the custom hooks directly through the Runtime.addshutdownhook (Thread Hook), implement the resource cleanup in the hook, and for the worker class application, we can safely exit the application in the following way. Signal-based process notification mechanism

The signal is a simulation of the interrupt mechanism at the software level, in principle, a process receives a signal and the processor receives an interrupt request can be said to be the same. In layman's terms, signal is an asynchronous communication mechanism between processes. The signal has platform dependencies, and some of the termination process signals supported by the Linux platform are shown below:

Signal name Use
SIGKILL Terminate process, Force kill process
Sigterm Terminate process, software abort signal
Sigtstp Stop the process, stop the signal from the terminal
Sigprof Terminate process, statistic distribution chart with timer to time
SIGUSR1 Terminate process, user-defined signal 1
SIGUSR2 Terminate process, user-defined signal 2
SIGINT Terminate a process, break a process
Sigquit Establish core file terminate process and generate core file

There are some differences in the Windows platform, and some of its signals are illustrated as follows:

Signal name Use
SIGINT CTRL + C Interrupt
Sigterm Termination of software sent by kill
Sigbreak Ctrl+break interrupted

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

With this signaling mechanism, the JVM can perceive and process the signal by sending a specific signal to the application JVM, which in turn can accept the program's exit instructions. Secure Exit Implementation

First look at the general JVM Security exit Flowchart:

The first step, when the application process starts, initializes the signal instance, which has the following code example:

1
Signal sig = new Signal (Getossignaltype ());

The parameters of the signal constructor are string strings, as well as the semaphore names described above.

The second step, according to the name of the operating system to get the corresponding signal name, the code is as follows:

1
2
3
4
5
Private String Getossignaltype ()
   {return
       system.getproperties (). GetProperty ("Os.name")
                 . toLowerCase (). StartsWith ("Win")? "INT": "USR2";
    }

Determine if it is the Windows operating system, if so, select SIGINT, receive CTRL + C interrupt instructions, or select USR2 signal, receive SIGUSR2 (equivalent to kill-12 pid) instructions.

The third step is to register the instantiated Signalhandler with the signal of the JVM and, once the JVM process receives kill-12 or CTRL + C, callback the handle interface, the code example reads as follows:

1
Signal.handle (SIG, Shutdownhandler);

Where Shutdownhandler implements the handle (Signal Sgin) method of the Signalhandler interface, the code example reads as follows:

1
2
3
4
5
6 7 8 9
public class Shutdownhandler implements Signalhandler {
    /**
     * processing Signal
     *
     * @param signal signal * *
     Public
    void handle (Signal Signal) {
    }
}

Step fourth, in the handle interface that receives the signal callback, initializes the Shutdownhook thread of the JVM and registers it with the runtime, as shown in the sample code:

1
2
3
4
5
private void Registershutdownhook ()
 {
        thread t = new Thread (new Shutdownhook (), "Shutdownhook-thread");
        Runtime.getruntime (). Addshutdownhook (t);
 

Step fifth, after receiving the process exit signal, performs the virtual machine exit operation in the callback's handle interface with the sample code as follows:

1
Runtime.getruntime (). exit (0);

When the JVM exits, the bottom automatically detects whether the user has registered the Shutdownhook task, and if so, automatically executes the register hook's Run method, and the application only needs to be performed in Shutdownhook, sample code as follows:

1 2 3 4 5 6 7 8 9 
class Shutdownhook implements Runnable {@Override public void run () {SYSTEM.OUT.PRINTLN
                ("Shutdownhook Execute start ...");
                    try {TimeUnit.SECONDS.sleep (10);//process operation before exiting the simulation application process} catch (Interruptedexception e) {
                E.printstacktrace ();
                } System.out.println ("Shutdownhook Execute End ..."); }
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.