Young and old generations
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Most objects in a Java program live for a very short time: a string built for one response, an iterator for one loop. HotSpot's collectors use this fact by keeping new objects in a separate young generation that can be cleaned often and cheaply, and moving the few long-lived objects to an old generation.
Most objects die young: the generational idea
Generational collection splits the heap into a young generation for new objects and an old generation for long-lived ones, because most objects die young.
The weak generational hypothesis is the observation that most objects die young, and the few that survive a while tend to live long.
Example 1 · An exam-results server: millions of short-lived objects
public class ResultsServerDemo { public static void main(String[] args) { String[] recentResults = new String[20_000]; // "recently viewed" list: lives a while long chars = 0; for (int i = 0; i < 6_000_000; i++) { String result = "Roll-" + i + ": PASS"; // built for one request: dies young chars += result.length(); if (i % 10 == 0) { recentResults[(i / 10) % recentResults.length] = result; } } System.out.println("Requests served: 6000000"); System.out.println("Characters sent: " + chars); }}Requests served: 6000000 Characters sent: 106888890
What this code does
- Each request builds a
resultstring that is garbage one loop step later. Only every tenth result is stored, and the 20,000-slotrecentResultsarray overwrites old entries, so those die a little later. - The array itself lives for the whole run. Run it with GC logging (next example) to see how few objects survive each young collection.
Example 2 · Young collections free almost everything
java -Xlog:gc ResultsServerDemo[0.034s][info][gc] Using G1 [0.248s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->1M(118M) 7.319ms [0.270s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 35M->2M(118M) 5.177ms [0.324s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 70M->2M(118M) 5.726ms [0.357s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 70M->2M(118M) 4.463ms [0.412s][info][gc] GC(4) Pause Young (Normal) (G1 Evacuation Pause) 70M->2M(236M) 6.790ms Requests served: 6000000 Characters sent: 106888890
What this code does
70M->2Mmeans 70 MB was in use before the collection and 2 MB after: over 95% of the young objects were already dead. This is the generational hypothesis in a real run.- Each pause took about 5 ms because only the 2 MB of survivors were copied. Times and sizes differ per machine (this run: HotSpot, Java 21, G1).
It is not a law, but it holds for most real programs, such as a server that builds response objects for each request. So HotSpot splits the heap into two generations: the young generation for new objects and the old generation for objects that have survived several collections. The young generation is collected often; because almost everything there is dead, each collection copies only a few survivors and is fast.
Eden and the two survivor spaces
The young generation has three parts. Eden is where new objects are created (inside TLABs). The two survivor spaces, often called S0 and S1 or "from" and "to", hold objects that survived at least one young collection.
jcmd <pid> GC.heap_infodef new generation total 36288K, used 3232K [...] eden space 32320K, 10% used [...] from space 3968K, 0% used [...] to space 3968K, 0% used [...] tenured generation total 80576K, used 0K [...] the space 80576K, 0% used [...] Metaspace used 143K, committed 384K, reserved 1114112K class space used 6K, committed 128K, reserved 1048576K
At a young collection, the live objects in eden and in the "from" survivor are copied into the empty "to" survivor. Eden and "from" are then completely empty, and the two survivor spaces swap roles. One survivor space is always empty, ready for the next copy.
This is how the Serial and Parallel collectors lay out the heap. With jcmd <pid> GC.heap_info on a JVM started with -XX:+UseSerialGC you can see eden, "from" and "to", with eden about eight times the size of each survivor space (SurvivorRatio is 8 by default). Addresses are trimmed below.
Object age, tenuring and promotion to the old generation
Every object has an age: the number of young collections it has survived, kept in its header. Each time a young collection copies it into a survivor space, its age goes up by one.
Example 3 · Simulation: eden, a survivor space and promotion
import java.util.ArrayList;import java.util.List;
class Obj { String name; int collectionsToLive; int age = 0;
Obj(String name, int collectionsToLive) { this.name = name; this.collectionsToLive = collectionsToLive; }
@Override public String toString() { return name + "(age " + age + ")"; }}
public class GenerationsDemo { static final int THRESHOLD = 3; // small so promotion shows; HotSpot's maximum is 15 static List<Obj> eden = new ArrayList<>(); static List<Obj> survivor = new ArrayList<>(); static List<Obj> old = new ArrayList<>();
static void youngGc(int number) { int scanned = eden.size() + survivor.size(); int oldBefore = old.size(); List<Obj> to = new ArrayList<>(); List<Obj> live = new ArrayList<>(survivor); live.addAll(eden); for (Obj o : live) { if (o.age >= o.collectionsToLive) { continue; } o.age++; if (o.age >= THRESHOLD) { old.add(o); } else { to.add(o); // copied to the other survivor space } } eden.clear(); survivor = to; // the two survivor spaces swap roles int kept = survivor.size() + (old.size() - oldBefore); System.out.println("GC " + number + ": " + scanned + " young objects, " + kept + " kept"); System.out.println(" survivor: " + survivor); System.out.println(" old: " + old); }
public static void main(String[] args) { eden.add(new Obj("order1", 0)); eden.add(new Obj("order2", 0)); eden.add(new Obj("receipt", 0)); eden.add(new Obj("session", 2)); eden.add(new Obj("config", 99)); youngGc(1);
eden.add(new Obj("temp1", 0)); eden.add(new Obj("temp2", 0)); eden.add(new Obj("cart", 1)); youngGc(2);
eden.add(new Obj("temp3", 0)); youngGc(3); }}GC 1: 5 young objects, 2 kept survivor: [session(age 1), config(age 1)] old: [] GC 2: 5 young objects, 3 kept survivor: [session(age 2), config(age 2), cart(age 1)] old: [] GC 3: 4 young objects, 1 kept survivor: [] old: [config(age 3)]
What this code does
- A simplified model:
collectionsToLivesays how many young collections an object survives. Dead objects are never copied, so the work of each GC depends only on the few that are kept. Live objects are copied intoto, the empty survivor space. configsurvives GC 1 and GC 2 in the survivor space and reaches age 3 at GC 3, so it is promoted toold.sessiondies after 2 collections andcartafter 1, so neither is ever promoted.
Example 4 · Watching ages in a real JVM
java -Xlog:gc+age=trace ResultsServerDemo[0.204s][debug][gc,age] GC(0) Desired survivor size 1572864 bytes, new threshold 15 (max threshold 15) [0.214s][trace][gc,age] GC(0) Age table with threshold 15 (max threshold 15) [0.214s][trace][gc,age] GC(0) - age 1: 1978968 bytes, 1978968 total [0.247s][debug][gc,age] GC(1) Desired survivor size 2621440 bytes, new threshold 15 (max threshold 15) [0.255s][trace][gc,age] GC(1) Age table with threshold 15 (max threshold 15) [0.255s][trace][gc,age] GC(1) - age 1: 1280032 bytes, 1280032 total [0.255s][trace][gc,age] GC(1) - age 2: 698816 bytes, 1978848 total ... [0.385s][trace][gc,age] GC(4) Age table with threshold 15 (max threshold 15) [0.385s][trace][gc,age] GC(4) - age 1: 1280040 bytes, 1280040 total [0.385s][trace][gc,age] GC(4) - age 4: 32 bytes, 1280072 total [0.385s][trace][gc,age] GC(4) - age 5: 698816 bytes, 1978888 total Requests served: 6000000 Characters sent: 106888890
What this code does
- About 1.3 MB of recent results survive each collection at age 1 and are dead by the next one. A group of about 0.7 MB, the long-lived array plus some JVM start-up objects, gets one age older at every GC: 1, 2, ... 5.
- "threshold 15 (max threshold 15)" is the tenuring threshold for this run. That long-lived group would be promoted to the old generation at age 15. The "..." marks trimmed lines; your numbers will differ.
When the age reaches the tenuring threshold, the next young collection copies the object into the old generation instead. This move is called promotion (or tenuring). On HotSpot the maximum threshold is 15 (-XX:MaxTenuringThreshold, default 15), and the JVM lowers the actual threshold when the survivor space gets too full. Objects can also be promoted early: if the survivor space has no room left, the overflow goes straight to the old generation, whatever its age.
In G1 the generations are sets of regions
G1, the default collector of HotSpot on most machines since Java 9, splits the heap into many equal-size regions.
jcmd <pid> GC.heap_infogarbage-first heap total 120832K, used 2048K [...] region size 1024K, 2 young (2048K), 0 survivors (0K) Metaspace used 143K, committed 384K, reserved 1114112K class space used 6K, committed 128K, reserved 1048576K
On Java 17 and 21 a region is 1 MB to 32 MB by default, chosen from the heap size; on a machine with a 2 GB maximum heap it is 1 MB.
Each region has one role at a time: eden, survivor, old, humongous or free. A "generation" in G1 is just the set of regions with that role, not a fixed block of memory. After a young collection the emptied eden regions become free, and G1 can grow or shrink the young generation between collections to meet its pause-time goal.
Example 5 · Region counts per generation in G1
java -Xlog:gc,gc+heap=info ResultsServerDemo[0.021s][info][gc] Using G1 [0.317s][info][gc,heap] GC(0) Eden regions: 23->0(34) [0.317s][info][gc,heap] GC(0) Survivor regions: 0->2(3) [0.317s][info][gc,heap] GC(0) Old regions: 0->0 [0.317s][info][gc,heap] GC(0) Humongous regions: 0->0 [0.317s][info][gc ] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 23M->2M(118M) 29.030ms [0.338s][info][gc,heap] GC(1) Eden regions: 34->0(68) [0.338s][info][gc,heap] GC(1) Survivor regions: 2->2(5) [0.338s][info][gc,heap] GC(1) Old regions: 0->0 [0.338s][info][gc,heap] GC(1) Humongous regions: 0->0 [0.338s][info][gc ] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 36M->2M(118M) 5.048ms ...
What this code does
Eden regions: 23->0(34)reads: 23 eden regions before the GC, 0 after, and G1 plans 34 eden regions until the next one. The young generation grew from 23 to 34 and then 68 regions: in G1 its size is not fixed.- Survivors fit in 2 regions and nothing reached the old generation yet. With 1 MB regions on this machine, 23 regions is the 23M in the pause line.
Humongous objects in G1
In G1, an object that is at least half a region in size is humongous. It is never created in eden: G1 places it straight into one or more contiguous free regions of its own, counted as part of the old generation.
Example 6 · Humongous arrays in a college ERP batch job
public class HumongousDemo { public static void main(String[] args) { long total = 0; for (int day = 1; day <= 200; day++) { byte[] report = new byte[600 * 1024]; // 600 KB attendance report report[0] = (byte) day; total += report.length; } System.out.println("Reports built: 200"); System.out.println("Bytes allocated: " + total); }}Reports built: 200 Bytes allocated: 122880000
What this code does
- With 1 MB regions, each 600 KB report is humongous: it skips eden and takes a whole region. Run with
-Xlog:gc,gc+heap=infoand the log showsHumongous regions: 53->0and the cause(G1 Humongous Allocation)instead of(G1 Evacuation Pause). - 53 regions held 53 reports of 600 KB, so about 22 MB of those regions was empty space. G1 freed the dead humongous arrays already during a young pause, but reusing one buffer would avoid the waste altogether.
Humongous objects are costly. A 600 KB array in 1 MB regions occupies a whole region and wastes the remaining 424 KB, and many of them can trigger extra collections. If a program creates many large arrays, reusing a buffer or reading data in smaller chunks usually helps.
Next step
Check your understanding
12 quick questions