Java Garbage Collection after heap memory crosses a threshold

1.5k views Asked by At

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

2

There are 2 answers

2
Eugene On BEST ANSWER

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.

1
Sergey Prokofiev 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!