← Back to Chapters

Garbage Collection Algorithms

?️ Garbage Collection Algorithms

? Quick Overview

Garbage Collection (GC) in Java is an automatic memory management process. The JVM uses different GC algorithms to reclaim unused objects, optimize memory usage, and minimize application pause times.

? Key Concepts

  • Heap is divided into Young Generation and Old Generation
  • Minor GC works on Young Generation
  • Major / Full GC works on Old Generation
  • Different algorithms focus on throughput, latency, or footprint

? Syntax / Theory

GC algorithms are selected using JVM flags. Each algorithm has different behavior in terms of pause time, memory usage, and CPU overhead.

Common GC Algorithms

  • Serial GC – Single-threaded, simple
  • Parallel GC – High throughput
  • CMS – Low pause (deprecated)
  • G1 GC – Balanced, region-based
  • ZGC – Ultra-low latency

? Code Example(s)

? View Code Example
// Example JVM options to enable G1 Garbage Collector
java -XX:+UseG1GC -Xms512m -Xmx1024m -jar app.jar
? View Code Example
// Simple Java program to create objects and trigger GC
public class GCExample {
public static void main(String[] args) {
for (int i = 0; i < 100000; i++) {
byte[] data = new byte[1024 * 1024];
}
System.out.println("Objects created");
}
}

? Interactive GC Simulation

Visualize the "Mark and Sweep" process. Allocate memory, then run GC to free up "dead" objects.

New Object Garbage Survivor

Heap is empty

Objects: 0

? Live Output / Explanation

When the program runs with GC logging enabled, the JVM prints information about memory allocation and garbage collection cycles.

Using -Xlog:gc helps analyze GC behavior in real applications.

✅ Tips & Best Practices

  • Use G1 GC for most modern server-side applications
  • Monitor GC logs before tuning JVM options
  • Avoid unnecessary object creation
  • Choose GC based on latency vs throughput needs

? Try It Yourself

  • Run the same program using Serial GC and G1 GC
  • Enable GC logging and compare pause times
  • Increase heap size and observe GC frequency