Video in progress

What does the JVM do when you call System.gc() from code?

It is only a request to the JVM that "you may run a GC", not a guarantee. On HotSpot it usually triggers a full GC, which can slow the application down, so it is almost never used in production code.

📖 Answer

The Javadoc says it explicitly: the call is a suggestion to the JVM. In practice HotSpot often carries it out and does a Full GC, meaning the whole heap is examined, and on a large heap this can take seconds.

Why it is bad:

  • it cleans the old generation too, causing an unnecessary long pause;
  • the GC knows better when to run: it watches the allocation rate;
  • a System.gc() hidden inside a library can "freeze" the whole service.

That is why some teams set the -XX:+DisableExplicitGC flag, after which the call does nothing. Be careful: code that worked with old NIO direct buffers could rely on System.gc().

When it is acceptable: inside a test or benchmark, to get to a "clean" state before measuring. But even there the result isn't guaranteed.