Video in progress
How do large collections affect the GC, and how do you manage that in a service with a 30 GB heap?
Large arrays become humongous objects in G1, taking separate regions and causing fragmentation; millions of small nodes increase marking and copying time. I manage this by giving collections an initial size, reducing the object count, and, if needed, changing the GC (ZGC).
📖 Answer
There are two different problems, and they need different solutions.
Large arrays. In G1, an object bigger than half a region is humongous. On a 30 GB heap a region is typically 16 MB, so that means an array bigger than 8 MB, for example the table of a HashMap with 2 million references, or the Object[] inside a big ArrayList. The problems:
- on a resize, a new humongous array is allocated and the old one becomes garbage, so for a short time you use double the memory;
- if no contiguous free regions can be found, it can go all the way to a Full GC;
- pauses in the GC log caused by
Humongous Allocation.
Lots of small objects. 50 million Nodes + boxed values: the GC walks them in every marking cycle. A structure like this in old gen also adds work to young collections through the card table.
What I do:
- Measure. Analyze the GC log with
-Xlog:gc*(GCeasy or by hand), and look at allocation andG1HumongousAllocationevents in JFR. - Give the size up front: the resizes and the temporary double copy go away.
- Reduce the object count: primitive collections, structures over arrays, more compact encoding of the data.
- Instead of one giant collection, split into several smaller ones (sharding): that drops below the humongous threshold and increases parallelism too.
- Choose the GC. If pauses break the SLO, Generational ZGC (JDK 21+) in many cases brings pauses below a millisecond, but costs more CPU and memory. I don't put it on prod without checking it in a load test.
Raising -XX:G1HeapRegionSize is also an option, but it affects the other regions too, so I treat it as a last resort.
Sign up to mark studied questions and save your progress.