javajvmgarbage-collection

Why can't JVM trigger GC when the system is idle but can only trigger GC when object allocation fails?


Whether it is G1, ZGC or SGC, it seems that GC can only be triggered when the allocation of a new object fails. If I do not allocate objects, then my space will always be occupied, even if my system is not used temporarily until the next allocation fails. If GC can be triggered when the system is idle, it can greatly save the used memory space and reduce the impact of STW on application threads. So how do you define system idleness? Maybe it is the number of active threads, maybe it is the CPU usage of the current process, or it may be left to the user to define.


Solution

  • Why can't JVM trigger GC when the system is idle but can only trigger GC when object allocation fails?

    In fact ... it can!!

    For the G1 garbage collector, you can configure the GC to run periodically, and set a CPU load threshold for triggering. For example, the Java 21 GC tuning guide lists these options for the G1 collector.

    -XX:G1PeriodicGCInterval=0 - The interval in ms to check whether G1 should trigger a periodic garbage collection. Set to zero to disable.

    -XX:+G1PeriodicGCInvokesConcurrent - If set, periodic garbage collections trigger a concurrent marking or continue the existing collection cycle, otherwise trigger a Full GC.

    -XX:G1PeriodicGCSystemLoadThreshold=0.0 - Threshold for the current system load as returned by the hosts getloadavg() call to determine whether a periodic garbage collection should be triggered. A current system load higher than this value prevents periodic garbage collections. A value of zero indicates that this threshold check is disabled.

    The Java 21 documentation doesn't list equivalent options for other collectors.