Why this matters
- The generational layout is why garbage collection is fast at all, and it rests on one empirical observation about how objects behave.
OutOfMemoryErrorhas several variants naming different regions, and the region tells you what kind of problem you have.- Tuning flags are meaningless until you know which space each one resizes.
The regions
- Young generation — where every new object is allocated. Subdivided into Eden and two survivor spaces.
- Old generation, also called tenured — objects that have survived several young collections.
- Metaspace — class metadata: field and method definitions, bytecode, the runtime constant pool. Native memory, outside the heap.
- Code cache — native code produced by the JIT compiler.
- Thread stacks — one per thread, holding frames. Native memory, not heap.
The weak generational hypothesis
The entire design rests on one observation that holds for almost all programs:
That is why a minor collection of a 500 MB young generation can take a few milliseconds: if only 2% of it survives, there are only 10 MB of objects to copy.
Eden and the survivor spaces
Young generation
┌──────────────────────────┬────────┬────────┐
│ Eden │ S0 │ S1 │
└──────────────────────────┴────────┴────────┘
new objects here one in use, one empty
The cycle
- All allocation happens in Eden, by bumping a pointer — about as cheap as a stack push.
- When Eden fills, a minor collection runs. Live objects are copied into the empty survivor space; Eden is then wholly empty.
- Objects already in a survivor space are copied to the other one, and their age counter increments.
- One survivor space is always empty, which is what makes the copy possible without extra space.
- An object whose age passes the tenuring threshold is promoted to the old generation.
An object is also promoted immediately if it is too large for Eden, or if the target survivor space fills up.
A million strings, almost all collected by cheap minor collections. Nothing reaches the old generation.
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 5 sections
- Minor and major collections
- Metaspace
- The flags worth knowing
- Observing the regions
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.