Is it possible to invoke a forceful garbage collection in java every time heap memory crosses a particular threshold ?
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.