Java中注册进程退出时的清理函数

本文深入探讨了Java中addShutdownHook机制的局限性,并通过实例展示了如何在jvm关闭时执行清理工作。然而,在特定情况下如使用SIGKILL信号终止虚拟机时,无法保证清理函数的执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java里利用addShutdownHook可以添加一个线程,在jvm关闭时调用,执行一些清理工作

public static void main(String[] args) throws InterruptedException {
Thread shutdownHook = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("jvm going down!do something here!");
}

});
Runtime.getRuntime().addShutdownHook(shutdownHook);

while (true) {
TimeUnit.SECONDS.sleep(1);
}

}


但是这个线程不能保证总是工作.
[quote]In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows. The virtual machine may also abort if a native method goes awry by, for example, corrupting internal data structures or attempting to access nonexistent memory. If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run. [/quote]
所以kill -9的时候,就不能保证这个清理函数的执行了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值