java中结束进程的方法_java关闭Process

java1.8之后,Process有了destroy和destroyForcibly方法,用来结束进程,一般结束进程的流程为:

terminate process with destroy()

allow process to exit gracefully with reasonable timeout

kill it with destroyForcibly() if process is still alive

但是在java1.8的实现中,下面是源码:

public Process destroyForcibly(){

destroy();

return this;

}

可以看到destroyForcibly和destroy是等效的,这样就有一个问题,如果一段时间后destroy无法关闭进程,那么destroyForcibly又怎么能保证能强制关闭进程呢?除此之外,如果新进程又开启了一个新的子进程,又如何关闭新的子进程呢?(虽然这是新进程的责任,但是在'强制关闭'的情况下,新进程应该无法保证能顺利的关闭子进程)。

在java9+中,Process有了一个新的方法:toHandle,可以获取到 ProcessHandle对象,这个对象也有 destroy和destroyForcibly这两个方法,看了下它们的实现,是一个native方法

private static native boolean destroy0(long pid, long startTime, boolean forcibly);

应该比Process的更加可靠,至少强制关闭看起来不再是自欺欺人,而ProcessHandle还提供了一个children方法:

Returns a snapshot of the current direct children of the process.The parent of a direct child process is the process.Typically, a process that is not alive has no children.

这个方法可以获取进程的直接子进程,通过

p.children().forEach(ProcessHandle::destroy);

可以关闭它的直接子进程。如果这还不够,还有一个descendants方法,可以返回直接子进程以及子进程的子进程。

Returns a snapshot of the descendants of the process.The descendants of a process are the children of the processplus the descendants of those children, recursively.Typically, a process that is not alive has no children.

所以java9以及以后

ProcessHandle handle = p.toHandle();

handle.destroy();

handle.descendants().forEach(ProcessHandle::destroy);

应该是更好的关闭方法

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值