java的关闭钩子(Shutdown Hook)
来源:互联网 发布:网络情歌对唱视频 编辑:程序博客网 时间:2024/06/10 07:37
Runtime.getRuntime().addShutdownHook(shutdownHook);
用途
1应用程序正常退出,在退出时执行特定的业务逻辑,或者关闭资源等操作。
2虚拟机非正常退出,比如用户按下ctrl+c、OutofMemory宕机、操作系统关闭等。在退出时执行必要的挽救措施。
public class JVMHook {
public static void start(){
System.out.println("The JVM is started");
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
try{
//do something
System.out.println("The JVM Hook is execute");
}catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) {
start();
System.out.println("The Application is doing something");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出结果:
The JVM is started
The Application is doing something
The JVM Hook is execute
最后一条是三秒后JVM关闭时候输出的。
System.out.println("The JVM is started");
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run(){
try{
//do something
System.out.println("The JVM Hook is execute");
}catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static void main(String[] args) {
start();
System.out.println("The Application is doing something");
byte[] b = new byte[500*1024*1024];
System.out.println("The Application continues to do something");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出结果:
The JVM is started
The Application is doing something
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.java.seven.JVMHook.main(JVMHook.java:24)
The JVM Hook is execute
在OutOfMemoryError的时候可以做一些补救措施。
建议:同一个JVM最好只使用一个关闭钩子,而不是每个服务都使用一个不同的关闭钩子,使用多个关闭钩子可能会出现当前这个钩子所要依赖的服务可能已经被另外一个关闭钩子关闭了。为了避免这种情况,建议关闭操作在单个线程中串行执行,从而避免了再关闭操作之间出现竞态条件或者死锁等问题。
- java的关闭钩子(Shutdown Hook)
- JAVA虚拟机关闭钩子(Shutdown Hook)
- JAVA虚拟机关闭钩子(Shutdown Hook)
- JAVA虚拟机关闭钩子(Shutdown Hook)
- shutdown hook(关闭钩子)的用处-程序关闭之前要做的事情
- Wordpress的钩子(hook)
- Java关闭钩子的应用
- TP框架----hook(钩子)的使用
- hook钩子的使用
- 钩子(hook)
- 钩子运行机制(HOOK)
- 什么是钩子(Hook)
- HOOK钩子 (转载)
- 钩子(HOOK)
- 创建钩子(Hook)
- Hook(钩子)函数
- 钩子(hook)
- 钩子(hook)
- poj 1298 史上最难的问题 -- 凯撒密码
- 高级CSS filters
- PHP 的 preg_match 和 preg_match_all
- 解决Android SDK Manager不能连接网络
- docx转为html时给关键字标色
- java的关闭钩子(Shutdown Hook)
- 文本处理
- CUDA之——VS调试出现“无法查找或打开 PDB 文件”的警告
- iOS-OC-把JSON字符串转化为字典
- poj 1979 Red and Black -- dfs
- HDU 2767 Proving Equivalences (强联通)
- JavaScript邮箱验证
- SVN分支/合并原理及最佳实践
- iOS获取所有照片