如何优雅地停止java进程? [英] How to stop java process gracefully?

查看:39
本文介绍了如何优雅地停止java进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Linux 和 Windows 中优雅地停止 Java 进程?

How do I stop a Java process gracefully in Linux and Windows?

Runtime.getRuntime().addShutdownHook 什么时候被调用,什么时候不调用?

When does Runtime.getRuntime().addShutdownHook get called, and when does it not?

终结器呢,它们在这里有帮助吗?

What about finalizers, do they help here?

我可以从 shell 向 Java 进程发送某种信号吗?

Can I send some sort of signal to a Java process from a shell?

我正在寻找最好的便携式解决方案.

I am looking for preferably portable solutions.

推荐答案

关闭钩子在 VM 没有被强行杀死的所有情况下都会执行.因此,如果您要发出标准"kill(来自kill 命令的SIGTERM),那么它们将执行.类似地,它们会在调用System.exit(int)后执行.

Shutdown hooks execute in all cases where the VM is not forcibly killed. So, if you were to issue a "standard" kill (SIGTERM from a kill command) then they will execute. Similarly, they will execute after calling System.exit(int).

然而,硬杀死(kill -9kill -SIGKILL)然后它们将不会执行.类似地(并且显然),如果您从计算机上取电,将其放入沸腾的熔岩桶中,或者用大锤将 CPU 打成碎片,它们将不会执行.不过,您可能已经知道这一点.

However a hard kill (kill -9 or kill -SIGKILL) then they won't execute. Similarly (and obviously) they won't execute if you pull the power from the computer, drop it into a vat of boiling lava, or beat the CPU into pieces with a sledgehammer. You probably already knew that, though.

终结器确实也应该运行,但最好不要依赖它来进行关闭清理,而是依靠你的关闭钩子来干净地停止事情.而且,一如既往,要小心死锁(我已经看到太多的关闭钩子挂起整个过程)!

Finalizers really should run as well, but it's best not to rely on that for shutdown cleanup, but rather rely on your shutdown hooks to stop things cleanly. And, as always, be careful with deadlocks (I've seen far too many shutdown hooks hang the entire process)!

这篇关于如何优雅地停止java进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆