Video in progress

Strong Junior ⚙️ JVM and memory

What do you gain by setting -Xms and -Xmx to the same value?

The heap is allocated at its maximum size from the start, and the JVM doesn't spend time growing or shrinking it while running. On servers this gives steadier latency, but the memory is never returned to the OS.

📖 Answer

-Xms is the initial heap and -Xmx is the maximum. When they differ, the JVM starts with a small heap and grows it after a GC if needed. Every resize means extra GCs and requests for memory from the OS.

java -Xms2g -Xmx2g -jar app.jar

For a server application I usually do this because:

  • the machine or container is dedicated to this one service, so there is no point in saving memory;
  • there are no needless GCs in the first minutes after startup;
  • a memory shortage shows up at startup, not at midnight.

On top of that, -XX:+AlwaysPreTouch actually touches the heap pages at startup. Startup gets slower, but there are no page faults later.

If you have a desktop app or many small services on one machine, different values are useful instead: an idle application doesn't sit on memory. In newer versions G1 and ZGC can return unused memory to the OS, but never below Xms.