Video in progress

Does the JVM return free heap memory to the operating system? How does that work in G1 and ZGC?

It does, but only in limited cases and never below -Xms. G1 mostly shrinks the heap after a Full GC or Remark, and since JDK 12 it also returns memory through a periodic GC while idle. ZGC uncommits free memory by itself after a certain delay.

📖 Answer

Many people say "once Java takes memory, it never gives it back". That used to be partly true.

G1. It resizes the heap based on MinHeapFreeRatio/MaxHeapFreeRatio, but it does so during a Full GC and the Remark phase of the concurrent cycle. If an application uses 3 GB during the day and sits idle at night, the GC is hardly ever invoked and the memory stays held. JDK 12 (JEP 346) added a periodic GC for exactly this:

-XX:G1PeriodicGCInterval=300000   # concurrent cycle after 5 minutes of inactivity

ZGC. Since JDK 13 it returns free memory by itself: -XX:ZUncommitDelay=300 (seconds, the default). You turn it off with -XX:-ZUncommit.

Parallel and Serial can also shrink the heap, but only during a GC.

A rule that holds for all of them: the heap never goes below -Xms. So if you set -Xms = -Xmx, returning memory is practically switched off.

When does this matter? If a node runs many JVMs, or the load changes sharply during the day, returned memory can serve other pods. In Kubernetes, though, the limit is strict anyway and the scheduler looks at the request, so many teams do the opposite: they set -Xms=-Xmx, reserve the memory up front and choose predictable behavior. Both are right, depending on the situation.