1.使用场景
- 当程序正常退出,系统调用 System.exit方法
- 虚拟机被关闭时
- 程序抛出异常时
- 可通过这些钩子在jvm关闭的时候进行内存清理、资源回收等工作
通过我们的程序中运行完之后都会进行一些清理工作,比如关闭数据库资源,同步等操作。这时我们的钩子函数addShutdownHook有了用武之地。
2.用法
Runtime.getRuntime().addShutdownHook(Thread thread)
3.实战
public
class CaptureException{
public static void main(String[] args){
Runtime.getRuntime().addShutdownHook(new Thread(()->{
System.out.println("The application will exit");
notifyAndRelease();
} ));
int i = 0;
while (true){
try{
Thread.sleep(1_000L);
}catch(Throwable e){
//ignore
}
System.out.println("I am working...");
i++;
if (i > 20) throw new RuntimeException("error");
}
}
public static void notifyAndRelease(){
System.out.println("notify to the admin");
try{
Thread.sleep(1_000L);
}catch(Throwable e){
//ignore
}
System.out.println("Will release resource(file,socket,connections)");
try{
Thread.sleep(1_000L);
}catch(Throwable e){
//ignore
}
System.out.println("Release done");
}
}
-------------------------------------------------------------------------------------------
kill 128964
[root@localhost java]# java -cp . CaptureException
I am working...
...
I am working...
The application will exit
notify to the admin
I am working...
Will release resource(file,socket,connections)
I am working...
Exception in thread "main" java.lang.RuntimeException: error
at CaptureException.main(CaptureException.java:17)
Release done
-------------------------------------------------------------------------------------------