英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论