Generational collection
Most objects die young, so the collector checks the newest ones far more often than the rest.
Open this lesson in the learning hubKey points
- The weak generational hypothesis: most objects become garbage almost immediately. Real programs really do behave like this.
- So the heap is split. New objects land in eden, survivors move to a survivor space, and old-timers are promoted to old.
- A young collection only scans the young area. It is quick precisely because nearly everything in there is already dead.
- Copying the survivors also compacts them, so allocation stays a cheap pointer bump instead of a free-list search.
- A full collection walks the old generation too. Those are the slow ones you notice in GC logs.
- Objects promoted too fast fill up old gen and force more full collections. That is what a leak looks like from the outside.
Example
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.List;
public class Main {
static Object sink; // stops the JIT deleting the allocation
public static void main(String[] args) {
List<GarbageCollectorMXBean> gcs = ManagementFactory.getGarbageCollectorMXBeans();
report(gcs, "at startup");
for (int i = 0; i < 2_000_000; i++) { sink = new byte[64]; } // ~128 MB of garbage
report(gcs, "after 2,000,000 short-lived arrays");
System.out.println("Young collections went up. Almost none of it survived.");
}
static void report(List<GarbageCollectorMXBean> gcs, String when) {
System.out.println(when + ":");
for (GarbageCollectorMXBean gc : gcs) {
System.out.printf(" %-24s collections=%-4d time=%d ms%n",
gc.getName(), gc.getCollectionCount(), gc.getCollectionTime());
}
System.out.println();
}
}
Cheap collections are cheap because they ignore the old stuff.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the JVM course, and every lesson in it is listed on the JVM contents page.