Video in progress
ZGC can keep pauses under a millisecond no matter how many gigabytes the heap is. How does it pull this off?
ZGC does almost all the work (marking, relocating objects and updating references) concurrently with the application. For that it uses colored pointers and a load barrier: if the application touches a relocated object, the barrier fixes the reference on the spot.
📖 Answer
In classic GCs the most expensive part is moving objects (compaction), because every reference pointing to them has to be updated. That is why the application is stopped.
ZGC's idea is different:
- every reference (pointer) carries a few metadata bits (the "color"): whether the object is marked, whether it is relocated;
- when the application reads a reference from the heap, a small check added by the JIT, the load barrier, runs;
- if the color is "stale", the barrier finds the object's new address in the forwarding table, fixes the reference and carries on.
As a result, stop-the-world is needed only at short synchronization points: mainly scanning the roots in thread stacks. That work depends on the number of threads, not on the heap size.
There is a cost too:
- a barrier on every reference read, so throughput can be a bit lower than G1;
- ZGC works concurrently, so it needs free space and CPU to keep up with the allocation rate. If it can't keep up, you see
Allocation Stallin the log: the application thread waits for memory; - it doesn't use compressed oops, so references are always 64 bit.
Java 21 added generational ZGC (-XX:+UseZGC -XX:+ZGenerational), and since Java 23 it is the default mode. Collecting young objects separately cuts allocation stalls considerably.
Sign up to mark studied questions and save your progress.