Skip to main content

Generational Garbage Collection

The Garbage Collector does not simply scan the entire heap memory every single time it runs. Scanning gigabytes of memory takes time, and doing it constantly would freeze your application (known as a "Stop-The-World" pause).

Instead, Java engineers made a statistical observation: Most objects created in Java die very quickly.

Based on this observation, the JVM divides the Heap Memory into different "Generations". This is known as Generational Garbage Collection.


The Heap Memory Architecture

Here is a visual representation of how Java organizes its memory:

1. The Young Generation

The Young Generation is where all newly created objects are allocated. Because most objects die quickly, the GC runs very frequently here. A garbage collection event in this region is called a Minor GC.

The Young Generation is subdivided into:

  • Eden Space: Every time you use the new keyword, the object is placed in Eden. When Eden is full, a Minor GC is triggered. All dead objects are deleted, and all surviving objects are moved to a Survivor space.
  • Survivor Spaces (S0 & S1): These are holding areas for objects that survived the Minor GC in Eden. Objects are constantly bounced between S0 and S1 during subsequent Minor GC cycles.

2. The Old (Tenured) Generation

If an object survives enough Minor GC cycles in the Survivor spaces (it reaches a certain "age" threshold), it is promoted to the Old Generation.

This space is much larger and is designed for long-lived objects. The GC runs much less frequently here. When it does run, it is called a Major GC. Major GCs are much slower and can cause noticeable pauses in application performance.

3. Metaspace (Formerly PermGen)

Metaspace is technically not part of the heap where your objects live. Instead, it is memory allocated from the native operating system to store metadata about your classes (like class definitions, method data, and static variables).

(Note: Prior to Java 8, this was called the Permanent Generation or PermGen, and it lived inside the JVM Heap, which notoriously caused OutOfMemoryError: PermGen space crashes).


The Promotion Process (Summary)

  1. You create an object: new Student(). It goes into Eden.
  2. Eden fills up. A Minor GC occurs.
  3. Unreachable objects in Eden are destroyed. Reachable objects are moved to Survivor 0.
  4. Eden fills up again. Another Minor GC occurs.
  5. Reachable objects from Eden and Survivor 0 are moved to Survivor 1.
  6. This bouncing back and forth between Survivor spaces continues.
  7. If an object survives 15 of these cycles (the default threshold), it is promoted to the Old Generation.