Runtime.getRuntime().addShutdownHook(shutdownHook);java
用途app
1应用程序正常退出,在退出时执行特定的业务逻辑,或者关闭资源等操做。jvm
2虚拟机非正常退出,好比用户按下ctrl+c、OutofMemory宕机、操做系统关闭等。在退出时执行必要的挽救措施。spa
示例:操作系统
package com.ebways.mq.test.hook; /** * JVM钩子 * Created by gmq on 2016/10/13 0013. */ public class JVMHook { public static void main(String[] args) { start(); // ==============================1: start========================== // 一、应用程序正常退出,在退出时执行特定的业务逻辑,或者关闭资源等操做。 // System.err.println("The Application is doing something"); // try { // Thread.sleep(3000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // ==============================1: end========================== // ==============================2: start========================== // 2、虚拟机非正常退出,好比用户按下ctrl+c、OutofMemory宕机、操做系统关闭等。在退出时执行必要的挽救措施。 System.err.println("The Application is doing something"); byte[] bytes = new byte[500 * 1024 * 1024]; throwException(); System.err.println("The Application continues to do something"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } // ==============================2: end========================== } private static void throwException() { throw new OutOfMemoryError("ASDF"); } public static void start() { System.err.println("The JVM is started"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { // do something System.err.println("The JVM Hook is execute!"); } catch (Exception e) { e.printStackTrace(); } } }); } }
控制台信息:线程
一、的状况code
The JVM is started The Application is doing something The JVM Hook is execute! Process finished with exit code 0
最后一条是三秒后JVM关闭时候输出的。对象
2:的状况blog
The JVM is started The Application is doing something Exception in thread "main" java.lang.OutOfMemoryError: ASDF at com.ebways.mq.test.hook.JVMHook.throwException(JVMHook.java:41) at com.ebways.mq.test.hook.JVMHook.main(JVMHook.java:28) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140) The JVM Hook is execute!
在OutOfMemoryError的时候能够作一些补救措施。内存
建议:同一个JVM最好只使用一个关闭钩子,而不是每一个服务都使用一个不一样的关闭钩子,使用多个关闭钩子可能会出现当前这个钩子所要依赖的服务可能已经被另一个关闭钩子关闭了。为了不这种状况,建议关闭操做在单个线程中串行执行,从而避免了再关闭操做之间出现竞态条件或者死锁等问题。