当我接近OutOfMemoryError时如何在java中确定?

Ari*_*iel 6 java runtime out-of-memory heap-size

我需要找出什么时候我真的很接近,OutOfMemoryError所以我可以将结果刷新到文件和调用runtime.gc();.我的代码是这样的:

Runtime runtime = Runtime.getRuntime();
...
if ((1.0 * runtime.totalMemory() / runtime.maxMemory()) > 0.9) {
... flush results to file ...
  runtime.gc();
}
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?有人可以帮我一把吗?

编辑

我明白我这样玩火,所以我推理一种更加坚实而简单的方法来确定我什么时候吃饱了.我目前正在使用Jena模型,所以我做了一个简单的检查:如果模型有超过550k的语句,那么我冲洗所以我不冒任何风险.

Sal*_*lah 3

首先:如果你想确定你是否接近OutOfMemoryError,那么你所要做的就是将当前内存与 所使用的最大内存进行比较JVM,以及你已经做了的事情。

第二:您想将结果刷新到文件,我想知道为什么您要这样做,只是如果您接近OutOfMemoryError,您只需使用类似 a 的东西,FileWriter它有一个缓冲区,所以如果缓冲区已满,它将自动刷新结果。

第三:永远不要GC显式调用,这是一种不好的做法,JVM而是优化你的内存参数:

-Xmx -> this param to set the max memory that the JVM can allocate
-Xms -> the init memory that JVM will allocate on the start up
-XX:MaxPermSize= -> this for the max Permanent Generation memory
Run Code Online (Sandbox Code Playgroud)

-XX:MaxNewSize=  -> this need to be 40% from your Xmx value
-XX:NewSize= -> this need to be 40% from your Xmx value
Run Code Online (Sandbox Code Playgroud)

这些将加速 GC。

-XX:+UseConcMarkSweepGC启用CMS旧空间的使用。