ProLesson 10.4Advanced3 min readUpdated 30 October 2026
Garbage collection basics
How the JVM decides what is garbage, why the heap is split into generations, and what minor GC, major GC and stop-the-world pauses mean.
In Java you create objects with new but never free them yourself. The garbage collector (GC) finds objects your program can no longer reach and reclaims their memory. Understanding the basics helps you avoid memory problems and answer GC questions with confidence.
01What counts as garbage: reachability
An object is alive if it can be reached by following references from a GC root. Everything else is garbage, even if objects still point at each other.
GC roots include:
- local variables and parameters on thread stacks,
- static fields of loaded classes,
- active threads,
- references held by native code (JNI).
Reachability.java
public class Reachability {
static class Node {
Node next;
final String name;
Node(String name) { this.name = name; }
}
public static void main(String[] args) {
Node a = new Node("A");
Node b = new Node("B");
a.next = b;
b.next = a; // a cycle
a = null;
b = null; // no root reaches A or B anymore → both are garbage,
// even though they still reference each other
System.out.println("A and B are now eligible for garbage collection");
}
}A and B are now eligible for garbage collection
Java's GC doesn't use reference counting, so cycles are collected fine.
Loading the rest of the lesson…