Video in progress
When G1 collects only the young generation, how does it find references from old to young? What are the card table and the remembered set?
To avoid scanning all of old, G1 uses a write barrier to mark which chunks of memory (cards) had a reference changed. Each region's remembered set stores who points into it from outside, so a young GC looks only at that small set.
📖 Answer
The problem: in a young GC, to find live objects you have to start from the roots. But an object in old can point to an object in young, and that is a root too. Walking an 8 GB old every time would make a minor GC pointless.
The solution has two layers:
- Card table: the heap is divided into 512-byte cards, with one byte for each. When the application writes
obj.field = other, the write barrier added by the JIT marks that card as "dirty". - Remembered set (RSet): in G1, one per region: "which cards of which regions have references into me". Dirty cards are processed in the background by refinement threads and recorded into the RSets.
In a young GC, roots = stacks, statics + the RSets of the young regions. Because of this, the pause depends not on the total heap size but on the amount of live data and the RSet size.
Practical consequences:
- code that changes references a lot (a big mutable graph, constant replacement in caches) spends more CPU on the write barrier and refinement;
- RSets take extra native memory. In NMT the
GCsection sometimes reaches 5-10% of the heap; - if the
Scan Heap RootsorMerge Heap Rootsphase is long in the log, the problem is in the RSets.
Sign up to mark studied questions and save your progress.