Java Memory Model
Garbage Collection
Understand JVM automatic memory management, reachability, GC roots, and generations.
Interview: Focuses on GC root definitions, object reachability stages, and the generational hypothesis (Young vs Old gen).
Java handles memory management automatically using Garbage Collection (GC). The GC identifies unreferenced, unreachable heap objects and reclaims their memory.
Core Idea
Objects are garbage collected when they are no longer reachable from any active GC Roots.
Why It Matters
Knowing GC generations helps developers select optimal JVM configurations to limit application pause times.
Interview Lens
Expect questions on what qualifies as a GC root and the mechanics of Minor vs Major collections.
Generational Memory Layout
The JVM divides the Heap into two generations based on the Weak Generational Hypothesis (most objects die young):
- Young Generation: Where new objects are allocated. Subdivided into Eden, and two Survivor spaces (S0/S1). Minor GC reclaims dead objects here.
- Old (Tenured) Generation: Holds long-lived objects promoted from the Young Generation after surviving multiple GC cycles. Major (Full) GC reclaims space here.
GC Roots and Reachability
An object is eligible for reclamation if it cannot be reached via a chain of references starting from a GC Root. GC Roots include:
- Local variables in active thread stacks.
- Active Java Threads.
- Static variables loaded in class metadata.
- JNI (Java Native Interface) global references.
Interview-Relevant Information
Q: Can objects participating in a circular reference cycle be garbage collected?
Answer: Yes. Java uses a reachability algorithm, not reference counting. If Object A points to Object B, and Object B points to Object A, but neither is reachable from any GC Root, both objects are collected.
Quick Checklist
Name three types of GC Roots. What is the Generational Hypothesis? If yes, you understand GC basics.
Use Cases
Tuning heap generation ratios on database servers to improve throughput.
Configuring memory allocation settings for microservices running in Docker containers.
Common Mistakes
Calling System.gc() in code. This is only a suggestion to the JVM, and calling it causes expensive, unnecessary Stop-The-World (STW) pauses.
Thinking objects are deleted immediately when they are dereferenced (they are only collected when the GC actually runs).