Application of the Java closure Hook-Shutdown Hook

Source: Internet
Author: User
Tags exit in terminates

Background

In development, when you encounter this situation, multiple threads work simultaneously, suddenly a thread encounters a fetal error, needs to terminate the program immediately, and then restart after the problem is resolved by manual troubleshooting. However, there is a problem that when the program terminates, other threads may be doing important things, such as sending a message to another module and updating the database state. A sudden termination may cause the operation to be half done, resulting in inconsistent data.

The solution is to refer to the database transaction the concept of atomicity, to consider this series of important operations as a whole, either complete or complete. For ease of expression, we take this series of important actions as Operation X.
When the program is about to exit, see if there is currently an operation x in the execution,

    • If there is, wait for it to complete and then exit. And no new operation X is accepted during the period. If the action x executes too long between, terminates and rolls back all states.
    • If not, you can exit immediately.

When the program exits, do some check to ensure the atomic nature of the operation X that has already started Runtime.ShutdownHook .

What is shutdown Hook

Shutdown hookis a initialized but unstarted thread. When the JVM starts executing shutdown sequence, all registered are run concurrently Shutdown Hook . At this point, the Shutdown Hook operation defined in this thread will start executing.

It is important to note that the Shutdown Hook operations performed in should be less time-consuming. Because in the case of the JVM shutdown, which is caused by the user logoff or the operating system shutdown, the system will only reserve a limited amount of time for unfinished work and will be forced to close after the timeout.

When will the shutdown Hook be called?
    • Program stops normally
      • Reach the end of program
      • System.exit
    • Program Exception exit
      • NPE
      • OutOfMemory
    • Be stopped by external influences
      • CTRL + C
      • User logoff or shutdown
How to use the shutdown Hook

Call java.lang.Runtime the method of this class to addShutdownHook(Thread hook) register one Shutdown Hook , and then define the operations that need to be done on system exit in thread. As follows:

Runtime.getRuntime().addShutdownHook(new Thread(() -> System.out.println("Do something in Shutdown Hook")));
Test examples

First, register a Shutdown Hook .
Then, the system sleep for 3 seconds, simulating some operations.
Then, call an empty list, throw an exception, and prepare to end the program.
When the program is going to end, the content is executed Shutdown Hook .

 Public Static void Main(string[] args) {//Register shutdown HookRuntime.GetRuntime().Addshutdownhook(NewThread ((), System. out.println("Do something in Shutdown Hook")));//Sleep for some time    Try{ for(intI=0; i<3; i++) {System. out.println("Count:"+ i +"..."); Timeunit.MILLISECONDS.Sleep( +); } List nulllist =NewArraylist<> (); System. out.println("Trying to print null list ' s first element:"+ nulllist.Get(0).toString()); }Catch(Interruptedexception e) {e.Printstacktrace(); } System. out.println("Ready to exit."); System.Exit(0);}

The results are as follows:

Count: 0...Count: 1...Count: 2...Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0    at java.util.ArrayList.rangeCheck(ArrayList.java:653)    at java.util.ArrayList.get(ArrayList.java:429)    at HookTest.main(HookTest.java:18)Do something in Shutdown HookProcess finished with exit code 1
Points to be aware of
    • System.exitafter that, Shutdown Hook the other threads will continue to execute when the execution begins.
    • Thread safety should be ensured Shutdown Hook .
    • Be Shutdown Hook especially careful when using multiple, and ensure that the service it calls is not affected by other hooks. Otherwise, the service that the current hook depends on is terminated by another hook.
Link
    • Java Doc-runtime
    • Java Virtual machine closed hook (Shutdown hook)

Application of the Java closure Hook-Shutdown Hook

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.