Advertisement
Advanced Java, Garbage Collection

How does the JVM's tri-color marking algorithm (used by concurrent garbage collectors like G1) work to identify reachable objects while application threads continue running concurrently, and what problem does a write barrier solve in this context?

Short answer

Tri-color marking conceptually assigns each object one of three colors during the mark phase: white (not yet visited, presumed garbage), grey (visited but its references not yet fully scanned), and black (visited AND all its references scanned) -- starting from GC roots (colored…

Save Java mock interview
Advertisement
AModel answer
Tri-color marking conceptually assigns each object one of three colors during the mark phase: white (not yet visited, presumed garbage), grey (visited but its references not yet fully scanned), and black (visited AND all its references scanned) -- starting from GC roots (colored grey), the algorithm repeatedly picks a grey object, colors it black, and colors all its referenced objects grey (if they were white), continuing until no grey objects remain, at which point remaining white objects are unreachable garbage; the challenge with performing this CONCURRENTLY while application threads keep running and mutating references is that an application thread could modify a reference in a way that would cause the marking algorithm to miss a reachable object (specifically: a black object gaining a new reference to a white object that has no other grey object referencing it) -- a write barrier (a small piece of code the JVM inserts around every reference-field write) detects and handles exactly this problematic mutation pattern, typically by re-coloring the newly-referenced object grey to ensure it still gets properly scanned despite the concurrent mutation.
// Conceptual illustration of what a write barrier intercepts (not actual user-visible code)
// When application code executes: blackObject.field = whiteObject;
// The JVM's inserted write barrier detects this specific black-to-white reference creation
// and takes corrective action (e.g., marking whiteObject grey) to prevent it from being
// incorrectly missed and collected as garbage despite now being reachable
Real-world example
A concurrent garbage collector like G1 relies on write barriers inserted transparently by the JIT compiler around every object reference assignment throughout the entire application, a small but pervasive per-write overhead that's the necessary cost of allowing GC marking to safely proceed concurrently with actively running, reference-mutating application threads.
Likely follow-ups
  • What's the performance overhead cost of write barriers, and how do different collectors balance this against pause time reduction?
  • How does this concurrent marking challenge relate to why STW (stop-the-world) pauses are still sometimes necessary even in a 'concurrent' collector?
Related topics