Card 09/ 09

RecapDifficulty: Advanced1 min

Recap: Stack, Heap and Garbage Collection

Two regions, one rule for what survives, two errors and one kind of leak, with where each was.

Memory in Java comes down to the five ideas below, each listed with the card that covers it.

What the topic established, and which card it was on
The ideaWhere
Variables live in stack frames; every object lives on the heapThe Stack and the Heap in Java
An object survives while a path from a root reaches it, and no longerGarbage Collection and Reachability
A stack overflow is recursion; an out-of-memory is reachable objectsStackOverflowError vs OutOfMemoryError
System.gc() requests a collection and cannot free anything reachableSystem.gc() Is Only a Suggestion
A leak is code holding references it has no use forMemory Leaks in Java: References You No Longer Need

Reachability, not usefulness, is the whole rule. The collector has no idea what you are finished with, so anything still on a path from a static field, a live frame or a running thread stays exactly where it is.