JAVA Virtual Machine Hooks

Source: Internet
Author: User

Shutdown Hook

Java programs often encounter process hangs, some states are not properly saved, this time you need to execute some cleanup code when the JVM shuts down. The Shutdownhook in Java provides a better Solution.

The JDK provides a Java.Runtime.addShutdownHook (Thread Hook) method that can register a JVM closed hook, which can be called in several scenarios:

    1. Program exits normally
    2. Using System.exit ()
    3. Interrupts triggered by the terminal using CTRL + C
    4. System shutdown
    5. OutOfMemory Downtime
    6. Kill the process using the Kill PID command (note: It is not called when using the kill-9 Pid)

Here is the definition of hooks in JDK1.7:

     public void addshutdownhook (Thread hook) parameters:     -an Initialized but unstarted Thread object thrown:     if  it can be determined, the hook is alread Y running or have already been run     -If the virtual machine was already in the process of shutting     /c10>-If A security manager is present and it denies runtimepermission ("shutdownhooks") starts from the following versions     :1.3 See also:    removeshutdownhook (java.lang.Thread), Halt (int), exit (int)

To test the first, the program exits normally:

Importjava.util.concurrent.TimeUnit;  public classHooktest { public voidstart () {runtime.getruntime (). Addshutdownhook (NewThread (NewRunnable () {@Override public voidrun () {System.out.println ("Execute Hook ...");      }          })); }        public Static voidmain (string[] Args) {Newhooktest (). Start (); System.out.println ("the application is doing something"); Try{TimeUnit.MILLISECONDS.sleep (5000); }          Catch(interruptedexception E) {e.printstacktrace (); }      }  }

Operation Result:

The application is doing something

Execute Hook .....

JAVA Virtual Machine Hooks

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.