在进行堆转储后,如何在 OutOfMemoryError 上重启 JVM?

How can I restart JVM on OutOfMemoryError _after_ making a heap dump?

我知道 -XX:+HeapDumpOnOutOfMemoryError JVM parameter. I also know about -XX:OnOutOfMemoryError="cmd args;cmd args" 并且 kill -3 <JVM_PID> 将请求堆转储。

问题: 我如何确保我在 OutOfMemoryError 上首先进行完整的堆转储,然后 然后 转储完成后强制重启(或终止)?我最好的选择是 -XX:OnOutOfMemoryError="kill -3 %p;sleep <time-it-takes-to-dump>;kill -9 %p" 吗?

我敢打赌运行时会在崩溃时设置特定的错误级别。检查 return 代码并在这种情况下重新运行程序。您也许应该将其放入脚本中。

sun jre 允许你在 oome 上堆转储,也许 openjdk 也可以。

java -XX:+HeapDumpOnOutOfMemoryError -XX:OnOutOfMemoryError="kill -9 %p" TestApp

JVM 会先转储堆,然后执行 OnOutOfMemoryError 命令(proof).

如果您只想关机,您可以使用以下参数之一:

  • -XX:+ExitOnOutOfMemoryError
  • -XX:+CrashOnOutOfMemoryError

在 Java 版本 8u92 中添加了 VM 参数,请参阅 release notes

ExitOnOutOfMemoryError
When you enable this option, the JVM exits on the first occurrence of an out-of-memory error. It can be used if you prefer restarting an instance of the JVM rather than handling out of memory errors.

CrashOnOutOfMemoryError
If this option is enabled, when an out-of-memory error occurs, the JVM crashes and produces text and binary crash files.

增强请求:JDK-8138745 (parameter naming is wrong though JDK-8154713ExitOnOutOfMemoryError 而不是 ExitOnOutOfMemory)