Java / Java 17 Garbage Collection Interview Questions
How does ZGC achieve sub-millisecond pause times using colored pointers?
ZGC repurposes unused bits within each 64-bit object reference to store metadata directly in the pointer itself - bits indicating things like marked0, marked1, remapped, and finalizable state. This is what's meant by a "colored" pointer: the color of a reference tells the runtime, at the moment it's read, whether that reference is still valid or needs fixing up.
Every heap reference load in application code passes through a load barrier the JIT inserts automatically. The barrier checks the pointer's color bits; if they indicate the reference is stale (for example, pointing at an object that has since been relocated), the barrier transparently "heals" it - fetching the correct, up-to-date address - before the application ever sees an invalid pointer.
Because this healing happens continuously and cheaply on ordinary reads spread across the whole concurrent phase, the bulk of the bookkeeping work that other collectors must do inside a stop-the-world pause (updating all the pointers to moved objects) is instead paid for gradually, one barrier check at a time, while the application keeps running. That's why ZGC's actual STW pauses can be reduced to just scanning roots - a cost that stays roughly constant no matter how large the heap grows.
More Related questions...