Video in progress
What happens when System.gc() is called in code, and why is blindly turning on -XX:+DisableExplicitGC dangerous?
In most GCs, System.gc() triggers a full stop-the-world Full GC. DisableExplicitGC turns it off, but NIO direct buffers try to clean up old buffers through exactly System.gc() when memory runs out. With it turned off, a "Direct buffer memory" OOM can appear.
📖 Answer
System.gc() is advice to the JVM, but HotSpot usually carries it out. In G1 and Parallel it is a full Full GC, which on a big heap is seconds. Who calls it? Sometimes a developer who wants to "clean up memory", sometimes a library, sometimes RMI (once an hour in older versions), sometimes a monitoring agent.
Finding out who: the GC log records the cause, Pause Full (System.gc()). Then you can look for the call site with JFR or thread dumps.
Now the trap. ByteBuffer.allocateDirect() takes memory outside the heap, and it is freed when the ByteBuffer object is collected by the GC. When the direct memory limit is reached, there is roughly this logic inside the JDK (java.nio.Bits): "no space → call System.gc() → wait a bit → try again". If DisableExplicitGC is on, that call does nothing and you get OutOfMemoryError: Direct buffer memory, even though dead buffers are sitting in the heap waiting to be collected. Netty, gRPC and Kafka clients use direct buffers heavily.
A better option:
-XX:+ExplicitGCInvokesConcurrent
In G1 and Shenandoah, System.gc() then starts a concurrent cycle instead of a stop-the-world Full GC. There is almost no pause, and the direct buffers still get cleaned.
And above all: remove System.gc() from your own code.
Sign up to mark studied questions and save your progress.