Java Garbage Collection


JVM Heap & Garbage Collection Basics


The GC Cycle

  1. Mark
    • Unused objects (those without live references) are identified
    • Simple approach: start from root objects, follow all references, and mark every reached object as live
  2. Sweep/Delete
    • Marked (dead) objects are removed
    • The allocator tracks the freed spaces for future allocations
  3. Compaction (optional)
    • Free spaces can become fragmented between live objects
    • The JVM may compact memory by shifting live objects to create one contiguous free region
  4. Reuse or Return
    • Freed memory is either returned to the OS or reused for new objects

GC Pause Modes


Generational Garbage Collection

Young Generation Layout


HotSpot GC Tuning

Key goals: pause-time, throughput, and heap size. HotSpot may adjust heap and GC frequency at runtime to meet targets.

Logging

-Xlog:gc*    # Log all GC-related messages

Pause-Time Goal

-XX:MaxGCPauseMillis=<ms>

Throughput Goal

-XX:GCTimeRatio=nnn

Heap Size

-Xms=<size>    # Initial (minimum) heap size  
-Xmx=<size>    # Maximum heap size (larger heaps ⇒ fewer GCs but longer pauses)

Generation Sizes

-XX:NewRatio=nnn    # Ratio of Old to Young gen size (default: 2)

Further Reading