0

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

  • I know this isn't overly helpful but maybe you should find out why your application is using so much memory and then try and reduce it if possible, or provide more memory. – Jason Apr 08 '20 at 21:32
  • Why? What's the point of doing that? What do you know that the JVM doesn't, that you "know better" when the GC needs to run? – Andreas Apr 08 '20 at 21:38
  • @Andreas though far stretched, but how about a report generation that takes a lot of time? What you would not want is more time introduced by a potential Full GC, so trigger a Full GC _before_ the report generation. I guess there could be other cases too - as there are tools that actually give you that ability. If there are tools that do that, there are people that need that, I guess. – Eugene Apr 08 '20 at 23:08
  • @Eugene The question isn't about triggering at some particular *point* in the code, e.g. before a report, which is already supported ([`System.gc()`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#gc--)), but about triggering on heap memory use threshold, i.e. to trigger a full GC when heap is e.g. 30% full, instead of letting the JVM decide for itself when partial and full GCs should be done. So I'm asking OP what the point is. Why would that be an improvement over the JVMs built-in logic, which has undergone lots of testing to be fine-tuned? – Andreas Apr 09 '20 at 02:05

2 Answers2

0

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!

Sergey Prokofiev
  • 1,815
  • 1
  • 12
  • 21
0

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.

Eugene
  • 117,005
  • 15
  • 201
  • 306