Video in progress

Strong Middle ⚙️ JVM and memory

What are compressed oops, and why can raising the heap slightly above 32 GB reduce your memory instead of increasing it?

On a 64-bit JVM, compressed oops store object references in 32 bits and, thanks to 8-byte alignment, can address a heap of up to 32 GB. When the heap goes beyond ~32 GB, references switch to 64 bits, objects grow and the usable space shrinks.

📖 Answer

On a 64-bit system a reference is naturally 8 bytes. In a Java application a noticeable share of objects is made of exactly such references (HashMap.Node, the array inside an ArrayList, DTO fields). The JVM plays a trick here: objects are aligned to 8 bytes, so the last 3 bits of an address are always zero. Multiplying a 32-bit number by 8 lets you address 2^32 × 8 = 32 GB.

The result: on a heap of up to 32 GB every reference is 4 bytes. On top of that, the class pointer is compressed too (compressed class pointers).

If you set the heap to -Xmx32g or -Xmx34g, the JVM silently turns compressed oops off. In an application with many references, objects grow by 20-40%, and a 34 GB heap in practice holds less data than a compressed heap of 28-30 GB. Fewer data also fit in the CPU caches.

To check:

java -Xmx31g -XX:+PrintFlagsFinal -version | grep UseCompressedOops   # true
java -Xmx33g -XX:+PrintFlagsFinal -version | grep UseCompressedOops   # false

The exact threshold is a bit lower, around 31 GB, because the heap base may not start at address zero. In practice I set -Xmx30g or lower, or jump straight to 48 GB+.

With -XX:ObjectAlignmentInBytes=16 you can raise the limit to 64 GB, but every object is then aligned to 16 bytes, and waste grows for small objects. ZGC does not use compressed oops at all, which is worth taking into account when you pick it.