Skip to main content
All tracks
Java Advanced

JVM Memory Model and Garbage Collection

Memory areas​

AreaHoldsLifetime
Stack (per thread)Method frames, local variables, referencesUntil the method returns
HeapObjects and arraysUntil unreachable and collected
MetaspaceClass metadataUntil the class loader is collected
Code cacheJIT-compiled codeJVM lifetime
void demo() {
int count = 3; // primitive: on the stack
StringBuilder sb = new StringBuilder(); // reference on the stack, object on the heap
process(sb);
} // frame popped; sb becomes unreachable

Garbage collection​

An object is eligible for collection when no live reference can reach it from a GC root (thread stacks, static fields, JNI).

ConceptMeaning
Generational hypothesisMost objects die young
Young generationNew objects (eden + survivor spaces); minor GCs are frequent and fast
Old generationLong-lived objects; major/mixed GCs are rarer and costlier
Stop-the-worldApplication threads paused during parts of GC

Collectors​

CollectorGoalNotes
G1 (default)Balanced throughput and pausesRegion-based, good general choice
ZGC / ShenandoahVery low pauses on large heapsMostly concurrent
ParallelMaximum throughputLonger pauses
SerialTiny heaps, single coreSimple
java -Xms512m -Xmx2g -XX:+UseG1GC -Xlog:gc* -jar app.jar

Common memory problems​

ProblemCauseFix
OutOfMemoryError: Java heap spaceHeap too small or a leakProfile with a heap dump; fix retention
Memory leakObjects kept reachable (static maps, listeners, caches without eviction)Remove references; bounded caches; weak references
StackOverflowErrorVery deep or infinite recursionConvert to iteration; fix base case
Long GC pausesLarge old generation, wrong collectorTune heap, try ZGC, reduce allocation

Tools​

  • jcmd, jstat, jmap for inspecting a running JVM.
  • Java Flight Recorder and VisualVM / Mission Control for profiling.
  • Heap dump analysis with Eclipse MAT.
TIP

Fix allocation hot spots before tuning GC flags. Most performance gains come from creating fewer objects, not from exotic JVM options.

Finished reading?

Mark it complete to track your progress across the docs.

Questions and discussion

Stuck on something here, or found a clearer way to explain it? Start a thread.

All discussions
  • Ask a question or share what helped
  • React to useful answers
  • Sign in with GitHub to post

Comments are stored in GitHub Discussions and shown here by giscus. PrepVerse never sees your GitHub password.