Java / Java 17 Garbage Collection Interview Questions
What are write barriers and load barriers, and how do collectors use them?
Both are small pieces of code the JIT compiler automatically inserts around reference field accesses, but they intercept different operations and serve different collector designs.
A write barrier runs after a reference field is written. G1 uses one to mark the card table dirty for cross-region reference updates (feeding remembered sets) and, during concurrent marking, to implement its SATB logging of overwritten reference values so the tricolor invariant holds.
A load barrier runs before a reference field is read, and is central to ZGC's design: it inspects a reference's colored-pointer bits and, if the object has been relocated since the pointer was last read, transparently fixes up ("self-heals") the pointer before returning it to the caller. Shenandoah achieves a similar effect with barriers around its Brooks-pointer indirection rather than pointer coloring.
Load barriers are inherently more expensive in aggregate than write barriers because reads vastly outnumber writes in typical programs, but they're what makes fully concurrent compaction (relocating live objects without a stop-the-world copy phase) possible at all - the extra per-read cost is the price paid for pause times that don't scale with heap size.
More Related questions...