Is it possible to invoke a forceful garbage collection in java every time heap memory crosses a particular threshold ?
Java Garbage Collection after heap memory crosses a threshold
1.5k views Asked by Jaharsh At
2
There are 2 answers
1
On
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!
This already happens. For example in
G1GC
, this is either when young space is full (for a minor collection) or whenInitiatingHeapOccupancyPercent
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 isShenandoahGCHeuristics
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.