Understanding JVM Garbage Collection Algorithms and Collectors

Garbage Collection Algorithms

Mark-Sweep Algorithm

Characteristics:

  • Fast collection speed
  • Causes memory fragmentation, making large contiguous allocations difficult

Process:

  1. First pass marks reachable objects from GC roots
  2. Second pass sweeps and reclaims memory from marked objects

Mark-Compact Algorithm

Advantages:

  • Eliminates memory fragmentation

Disadvantages:

  • Slower due to memory compaction

Copy Algorithm

Key Points:

  • Divides memory into two equal spaces (From and To)
  • Copies live objects from From to To space during collection
  • Swaps space designations after collection

Pros/Cons:

  • No fragmentation
  • Requires double memory space

Algorithm Comparison

Algorithm Advantages Disadvantages
Mark-Sweep Fast collection Memory fragmentation
Mark-Compact No fragmentation Slower performance
Copy No fragmentation High memory overhead

Generational Collection

Heap Strucutre:

  • Young Generation: Eden + Survivor spaces (From/To)
  • Old Generation: Long-lived objects

Collection Process:

  1. Objects allocated in Eden
  2. Minor GC triggers when Eden fills
  3. Surviving objects copeid to Survivor space
  4. Objects surviving multiple collections promoted to Old Gen
  5. Full GC occurs when Old Gen fills

Key Parameters:

-Xms - Initial heap size
-Xmx - Maximum heap size
-Xmn - Young generation size
-XX:SurvivorRatio - Eden/Survivor ratio
-XX:MaxTenuringThreshold - Promotion threshold

Garbage Collectors

Serial Collector

  • Single-threaded
  • Suitable for small heaps
  • Flags: -XX:+UseSerialGC

Throughput-Optimized Collector

  • Parallel collection
  • Maximizes application throughput
  • Flags:
-XX:+UseParallelGC
-XX:GCTimeRatio
-XX:MaxGCPauseMillis

Low-Pause Collector (CMS)

  • Concurrent marking
  • Minimizes pause times
  • Flags:
-XX:+UseConcMarkSweepGC
-XX:ConcGCThreads
-XX:CMSInitiatingOccupancyFraction

CMS Workflow:

  1. Initial mark (STW)
  2. Concurrent marking
  3. Remark (STW)
  4. Concurrent sweep

Tags: JVM garbage collection java Memory Management Performance

Posted on Tue, 15 Sep 2026 16:09:17 +0000 by parboy