鼓励 JVM 进行 GC 而不是增加堆?

(请注意,当我说JVM"时,我的意思是热点",我正在运行最新的 Java 1.6 更新.)

(Note that when I say "JVM", I really mean "Hotspot", and I'm running the latest Java 1.6 update.)

示例情况:

我的 JVM 运行时 -Xmx 设置为 1gb.目前,堆分配了 500mb,其中 450mb 被使用.该程序需要在堆上再加载 200 mb.目前,堆中有 300mb 的可收集"垃圾(我们假设它们都在最老的一代中.)

My JVM is running with -Xmx set to 1gb. Currently, the heap has 500mb allocated, of which 450mb is used. The program needs to load another 200 mb on the heap. Currently, there is 300mb worth of "collectable" garbage in the heap (we'll assume it's all in the oldest generation.)

在正常操作下,JVM 会将堆增加到 700 mb 左右,并在到达时进行垃圾收集.

Under normal operation, the JVM will grow the heap to 700 mb or so, and garbage collect when it gets around to it.

在这种情况下,我希望 JVM 先 gc,然后分配新的东西,这样我们最终的堆大小保持在 500mb,使用的堆大小保持在 350mb.

What I would like in that situation is for the JVM to gc first, then allocate the new stuff, so that we end up with the heap size staying at 500mb, and the used heap at 350mb.

是否有一个 JVM 参数组合可以做到这一点?

Is there a JVM parameter combo that does that?

推荐答案

你可以尝试指定 -XX:MinHeapFreeRatio-XX:MaxHeapFreeRatio 来控制堆的扩展和收缩:

You could try specifying -XX:MinHeapFreeRatio and -XX:MaxHeapFreeRatio to control heap expansion and shrinking:

  • -XX:MinHeapFreeRatio - 当一代中可用空间的百分比低于该值时,该代将扩展以满足该百分比.默认值为 40.
  • -XX:MaxHeapFreeRatio - 当一代中可用空间的百分比超过该值时,该代将收缩以满足该值.默认值为 70.
  • -XX:MinHeapFreeRatio - when the percentage of free space in a generation falls below this value the generation will be expanded to meet this percentage. Default is 40.
  • -XX:MaxHeapFreeRatio - when the percentage of free space in a generation exceeded this value the generation will shrink to meet this value. Default is 70.

您可能还想通过指定 -XX:+UseConcMarkSweepGC 来试验并发 GC.根据您的应用程序,它可以以额外的 CPU 周期为代价来降低堆大小.

You might also want to experiment with concurrent GC by specifying -XX:+UseConcMarkSweepGC. Depending on your application it could keep the heap size lower at the cost of additional CPU cycles.

JVM 会在最佳情况下使用您指定的可用内存.您可以指定一个较小的量,例如 -Xmx768m 以保持它包含在内并且它可能运行良好,尽管您会增加在重负载情况下耗尽内存的风险.真正使用更少内存的唯一方法是编写使用更少内存的代码:)

The JVM is otherwise going to use the memory you specify as available when it's optimal do to so. You could specify a lower amount like -Xmx768m to keep it contained and it might run fine, although you would increase your risk of running out of memory in a heavy load scenario. Really the only way to use less memory overall is to write code that uses less memory :)

相关文章