Using Java.lang.Runtime.addShutdownHook () Hook program to ensure the safe exit of Java program

Source: Internet
Author: User
Tags static class

It was previously only known at development time to rely on database transactions to guarantee data integrity when the program was closed.

But sometimes a business-required atomic operation does not necessarily include only databases, such as external interfaces or message queues. At this point the database transaction is helpless.

At this point we can rely on Java to provide a tool method: Java.lang.Runtime.addShutdownHook (Thread Hook)

The Addshutdownhook method can add a hook that triggers the hook when the program exits.

(exit refers to Ctrl + C or KILL-15, but if you use kill-9 that is no way, specifically on the signal mechanism of the kill of Daniel's article "Linux signal Signal processing mechanism")

Hooks can do anything, even check the state of a thread until the business thread exits normally, and then end the hook program to ensure the integrity of the business thread

Example procedures are as follows:

The instance program presses the CTRL-C or the kill-15 in the execution process, because the hook program's cyclic detection, can guarantee the thread execution completes, the program only then closes.

 1/** 2 * Created by IntelliJ idea.      3 * User:luo 4 * date:13-7-11 5 * Time: PM 3:12 6 * * 7 8 public class Testshutdownhook {9 10/** 11 * Test thread, used to simulate an atomic operation the private static class Taskthread extends Thread {@Override Publ
IC void Run () {System.out.println ("thread begin ...");
Testshutdownhook.sleep (1000);
SYSTEM.OUT.PRINTLN ("Task 1 OK ...");
Testshutdownhook.sleep (1000);
System.out.println ("Task 2 ok ...");
Testshutdownhook.sleep (1000);
System.out.println ("Task 3 OK ...");
Testshutdownhook.sleep (1000);
System.out.println ("Task 4 ok ...");
Testshutdownhook.sleep (1000);
System.out.println ("Task 5 ok ...");
SYSTEM.OUT.PRINTLN ("Thread end\n\n");     29} 30} 31 32/** 33 * Register Hook program to ensure full execution of the thread @param checkthread 35 * private static void Addshutdownhook (final Thread checkthread) {37//To ensure that Taskthread does not exit Midway, add Shutdownhoo K-Runtime.getruntime (). Addshutdownhook (New Thread () {$ public void run () {Sys
TEM.OUT.PRINTLN ("Receive shutdown signal, hook start, detect thread State ...");                     41//continuously detect the execution state, if the thread has not been executed, timeout, give up waiting for (int i = 0; i < i++) {43 if (checkthread.getstate () = = state.terminated) {System.out.println ("detects that the thread has finished executing
Bi, Exit hook ");
return;
Testshutdownhook.sleep (100);
SYSTEM.OUT.PRINTLN ("Detect timeout, give up waiting, exit hook, at this time the thread will be forced to close");
50} 51});         The private static void sleep (long Millis) {a try {thread.sleep (Millis); 58  catch (Interruptedexception e) {e.printstacktrace (); 60} 61   } string[public static void Main (] args) throws Interruptedexception {final Taskthread Taskthrea
D = new Taskthread ();
65//In order to ensure that taskthread not in the middle of the exit, add Shutdownhook Addshutdownhook (taskthread);
67//Executive Taskthread Taskthread.start (); 69} 70 71}


Http://www.cnblogs.com/baibaluo/p/3185925.html


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.