首页   快速返回

JAVA虚拟机关闭钩子Shutdown Hook使用     所属分类 java
关闭钩子Shutdown Hook 用于在jvm关闭之前执行定制的代码逻辑
譬如日志记录 资源清理 现场保护等


使用 Java.Runtime.addShutdownHook(Thread hook) 注册关闭钩子 

在以下场景会被调用 

程序正常退出
使用System.exit(int status) 退出jvm 
使用Ctrl+C终止运行
使用kill命令杀死进程(使用kill -9 时不会被调用)

测试代码 ShutdownHookTest.java

import java.util.Date;

public class ShutdownHookTest {
	public static void main(String[] args) throws Exception {
		System.out.println("ShutdownHookTest start "+new Date());
		
		Runtime.getRuntime().addShutdownHook(new HookThread());
		
		Thread.sleep(1000);
		
		String type = null;
		if(args!=null && args.length>0){
			type = args[0];
		}
		
		System.out.println("type="+type);
		if("error".equalsIgnoreCase(type)){
			throw new Exception("error");
		}
		
		if("wait".equalsIgnoreCase(type)){
			// sleep  ctrl+c  或 kill 
			Thread.sleep(1000000);
		}
		
		if("exit".equalsIgnoreCase(type)){
			System.exit(1);
		}
				
		System.out.println("ShutdownHookTest done "+new Date());
	}
	
	private static class HookThread extends Thread{
		public void run(){
			System.out.println("shutdown hook run "+new Date());
		}
	}

}

各种场景测试 

正常结束退出
java ShutdownHookTest
ShutdownHookTest start Sun Sep 30 18:22:39 CST 2018
type=null
ShutdownHookTest done Sun Sep 30 18:22:40 CST 2018
shutdown hook run Sun Sep 30 18:22:40 CST 2018

抛异常退出
java ShutdownHookTest error
ShutdownHookTest start Sun Sep 30 18:22:57 CST 2018
type=error
Exception in thread "main" java.lang.Exception: error
	at ShutdownHookTest.main(ShutdownHookTest.java:20)
shutdown hook run Sun Sep 30 18:22:58 CST 2018

使用System.exit 退出 
java ShutdownHookTest exit
ShutdownHookTest start Sun Sep 30 18:23:14 CST 2018
type=exit
shutdown hook run Sun Sep 30 18:23:15 CST 2018

使用ctrl+c 终止进程
java ShutdownHookTest wait
ShutdownHookTest start Sun Sep 30 18:23:23 CST 2018
type=wait
^Cshutdown hook run Sun Sep 30 18:23:25 CST 2018


使用kill 杀死进程
java ShutdownHookTest wait
ShutdownHookTest start Sun Sep 30 18:23:30 CST 2018
type=wait
shutdown hook run Sun Sep 30 18:23:58 CST 2018

使用kill -9 杀死进程
java ShutdownHookTest wait
ShutdownHookTest start Sun Sep 30 18:24:05 CST 2018
type=wait
Killed: 9

上一篇     下一篇
ExecutorService中submit和execute的区别

java thread join实现原理

java线程池shutdown和shutdownNow的区别

职场十大通用准则

客户忠诚的意义

处理人际关系的5条建议