Java - 关闭内存不足错误 [英] Java - shutting down on Out of Memory Error

查看:425
本文介绍了Java - 关闭内存不足错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说过如何最好地处理这个事情是非常矛盾的事情,我陷入了以下困境:

I've heard very contradictory things on how to best handle this, and am stuck with the following dilemma:


  • 一个OOME带来的一个线程,但不是整个应用程序

  • 我需要关闭整个应用程序,但不能因为线程没有剩余内存

我一直都知道最好的做法就是放手让JVM死掉,因为JVM在那时处于不一致状态,但似乎没有在这里工作。

I've always understood best practice is let them go so the JVM can die because the JVM is in an inconsistent state at that point, but that doesn't seem to be working here.

推荐答案

OutOfMemoryError 就像任何其他错误一样。如果它从 Thread.run()中逃脱,它将导致线程死亡。而已。此外,当线程死亡时,它不再是GC根,因此仅由此线程保留的所有引用都有资格进行垃圾回收。这意味着JVM很可能从OOME恢复。

OutOfMemoryError is just like any other error. If it escapes from Thread.run() it will cause thread to die. Nothing more. Also, when a thread dies, it is no longer a GC root, thus all references kept only by this thread are eligible for garbage collection. This means JVM is very likely to recover from OOME.

如果你想要杀死你的JVM而不管因为你怀疑它可能处于不一致状态,请将其添加到你的 java 选项:

If you want to kill your JVM no matter what because you suspect it can be in an inconsistent state, add this to your java options:

-XX:OnOutOfMemoryError="kill -9 %p"

%p 是当前Java进程PID占位符。剩下的就是自我解释。

%p is the current Java process PID placeholder. The rest is self-explained.

当然你也可以尝试捕捉 OutOfMemoryError 并以某种方式处理它。但这很棘手。

Of course you can also try catching OutOfMemoryError and handling it somehow. But that's tricky.

这篇关于Java - 关闭内存不足错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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