Java堆内存超过阈值后的垃圾回收

huangapple go评论67阅读模式
英文:

Java Garbage Collection after heap memory crosses a threshold

问题

在Java中,当堆内存越过特定阈值时是否可能调用强制垃圾回收?

英文:

Is it possible to invoke a forceful garbage collection in java every time heap memory crosses a particular threshold ?

答案1

得分: 0

理论上是的,你可以配置这种行为。具体细节取决于所使用的垃圾回收算法。例如,对于 CMS,当堆内存使用达到 70% 时,你可以启动垃圾回收。很可能你还希望设置初始内存和最大内存限制。

-XX:+UseConcMarkSweepGC -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70

希望对你有所帮助!

英文:

In theory yes, you could configure such behaviour. Exact details depend on used garbage collection alghoritm. For example, for CMS you can kick off GC when heap memory usage reaches 70%. Most probably you would also want to set initial and max memory limits.

-XX:+UseConcMarkSweepGC -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70

Hope it helps!

答案2

得分: 0

这已经在发生。例如,在G1GC中,这要么是在年轻代空间已满时(用于小型收集),要么是当达到InitiatingHeapOccupancyPercent设定值时(用于大型收集)。这两者都是通过标志进行控制的,因此您可以准确地知道何时会触发GC,如果您确实希望如此。

Shenandoah中,有ShenandoahGCHeuristics,它会选择一些启发式方法(它们也取决于大小)。

另一方面,如果您希望以编程方式实现(已经有工具可以实现此功能),您可以编写一些代码来检查堆的大小(例如通过ManagementFactory::getMemoryPoolMXBeans),然后通过代理调用进行操作。一般来说,您需要有非常充分的理由来这样做。

英文:

This already happens. For example in G1GC, this is either when young space is full (for a minor collection) or when InitiatingHeapOccupancyPercent is hit (for a major collection). Both of these are controlled via flags, so you can tell when exactly is a GC supposed to be triggered, IFF you really want that.

In Shenandoah there is ShenandoahGCHeuristics that will choose some heuristics (they do depend on the size too).

If, on the the other hand, you want to do that programmatically (there are tools that do that already), you could write some code that would inspect the size of the heap (for example via ManagementFactory::getMemoryPoolMXBeans) and then via an agent call. In general, you would need a very good reason to do this.

huangapple
  • 本文由 发表于 2020年4月9日 05:08:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/61110062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定