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:
- Program exits normally
- Using System.exit ()
- Interrupts triggered by the terminal using CTRL + C
- System shutdown
- OutOfMemory Downtime
- 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