Java Virtual machine closed hook (Shutdown hook)

Source: Internet
Author: User

Java programs often encounter a situation where a process hangs up. Some states are not properly saved, so it is necessary to run 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. The ability to register a JVM-closed hook. This hook 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)
followingIs the definition of hooks in JDK1.7:

public void Addshutdownhook (Thread hook)
Number of references:
Hook-an initialized but unstarted Thread object
Thrown:
Illegalargumentexception-if The specified hook has already been registered, or If it can be determined that the hook is Already running or has already been run
Illegalstateexception-if the virtual machine was already in the process of shutting down
Securityexception-if A security manager is present and it denies runtimepermission ("Shutdownhooks")
Start with the following version number:
1.3
See also:
Removeshutdownhook (Java.lang.Thread), halt (int), exit (int)

First of all, test the first, the procedure normal exit situation:

Package Com.hook;import Java.util.concurrent.timeunit;public class hooktest{public void Start () {Runtime.getruntime () . Addshutdownhook (New Thread (new Runnable () {@Overridepublic void run () {System.out.println ("Execute Hook ...");})); public static void Main (string[] args) {new Hooktest (). Start (); System.out.println ("The application is doing something"); Try{timeunit.milliseconds.sleep (5000);} catch (Interruptedexception e) {e.printstacktrace ();}}}
Execution Result:

The application is doing Somethingexecute Hook .....
As can be seen above. The close hook is called when the main thread finishes executing.

Here's a second test of the fifth case (the order is a bit messy, the table cares about these details):

Package Com.hook;import Java.util.concurrent.timeunit;public class hooktest2{public void Start () {Runtime.getruntime ( ). Addshutdownhook (New Thread (new Runnable () {@Overridepublic void run () {System.out.println ("Execute Hook ...");})); public static void Main (string[] args) {new Hooktest (). Start (); System.out.println ("The application is doing something"); byte[] B = new byte[500*1024*1024];try{ TimeUnit.MILLISECONDS.sleep (5000);} catch (Interruptedexception e) {e.printstacktrace ();}}}
The execution parameters are set to:-xmx20m This ensures that there will be outofmemoryerror to occur.

Execution Result:

The application is doing somethingexception in thread "main" Java.lang.OutOfMemoryError:Java Heap spaceat com.hook.HookTe St2.main (hooktest2.java:22) Execute Hook .....
Can see that the program has encountered a memory overflow error after calling close the hook. In the first case. The program waits for the 5000ms execution to launch after the call closure hooks are different.

And then we'll test the third case:

Package Com.hook;import Java.util.concurrent.timeunit;public class hooktest3{public void Start () {Runtime.getruntime ( ). Addshutdownhook (New Thread (new Runnable () {@Overridepublic void run () {System.out.println ("Execute Hook ...");})); public static void Main (string[] args) {new HookTest3 (). Start (); Thread thread = new Thread (new Runnable () {@Overridepublic void run () {while (true) {System.out.println ("thread is running Try{timeunit.milliseconds.sleep (100);} catch (Interruptedexception e) {e.printstacktrace ();}}}); Thread.Start ();}}
Compiling on the command line: Javac Com/hook/hooktest3.java

Execute at the command line: Java COM.HOOK.HOOKTEST3 (Press CTRL + C later)

Execution Result:
Can see the effect as expected.


There are several other cases that are not listed. Interested readers can try.

Java Virtual machine closed 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.