Lesson 2 of 8
Garbage Collection - Algorithms & Tuning
Garbage Collection automatically reclaims memory from objects no longer reachable. The choice of GC algorithm significantly affects throughput, latency, and memory footprint. Modern Java offers G1GC (default), ZGC, and Shenandoah as primary options.
GC Generations & Common Algorithms
- Minor GC - collects the Young Generation (Eden + Survivors). Very fast (milliseconds). Triggered when Eden is full.
- Major GC - collects the Old Generation. Slower (hundreds of ms). Triggered when Old Gen is low.
- Full GC - collects Young + Old + Metaspace. Very slow (seconds). Triggered by heap pressure.
- Serial GC (-XX:+UseSerialGC) - single thread. Best for small heaps on single-core.
- Parallel GC (-XX:+UseParallelGC) - multiple threads. High throughput, longer GC pauses.
- G1GC (-XX:+UseG1GC) - default Java 9+. Balanced throughput/latency. Divides heap into regions.
- ZGC (-XX:+UseZGC) - ultra-low latency (sub-millisecond pauses). Java 15+ production-ready.
- Shenandoah - low-pause, concurrent GC from RedHat. Similar goals to ZGC.
GC Tuning & Monitoring
// Key JVM flags for GC control
// -Xms512m Initial heap size
// -Xmx2g Maximum heap size (ALWAYS set equal to -Xms in production)
// -XX:+UseG1GC Use G1GC
// -XX:MaxGCPauseMillis=200 Target max GC pause (G1GC tries to meet this)
// -XX:+PrintGCDetails Print GC details (Java 8)
// -Xlog:gc*:file=gc.log:time,uptime Unified GC logging (Java 9+)
// -XX:+HeapDumpOnOutOfMemoryError Capture heap dump on OOM
// -XX:HeapDumpPath=/tmp/heap.hprof
// Measuring GC impact in code
public class GCDemo {
public static void main(String[] args) {
Runtime rt = Runtime.getRuntime();
System.out.printf("Max heap: %d MB%n", rt.maxMemory() / 1_048_576);
System.out.printf("Total heap: %d MB%n", rt.totalMemory() / 1_048_576);
System.out.printf("Free heap: %d MB%n", rt.freeMemory() / 1_048_576);
System.out.printf("Used heap: %d MB%n",
(rt.totalMemory() - rt.freeMemory()) / 1_048_576);
// Suggest GC (JVM may ignore - not guaranteed)
System.gc(); // usually called for benchmarking, not production
// Check if GC ran (use MXBean for real monitoring)
var gcBeans = java.lang.management.ManagementFactory.getGarbageCollectorMXBeans();
for (var gc : gcBeans) {
System.out.printf("GC: %-20s | Collections: %d | Time: %d ms%n",
gc.getName(), gc.getCollectionCount(), gc.getCollectionTime());
}
}
// Object reachability - GC can collect once unreachable
// Strong reference: Book b = new Book(...) - never collected while b holds it
// WeakReference: cleared by GC at any time
// SoftReference: cleared only when memory is low (good for caches)
// PhantomReference: sentinel - used for post-GC cleanup actions
static void demonstrateWeakRef() {
var weak = new java.lang.ref.WeakReference<>(new Book("001","Test","Author",0));
Book book = weak.get(); // may return null if GC ran
if (book != null) {
System.out.println("Still alive: " + book.getTitle());
}
System.gc();
System.out.println("After GC: " + weak.get()); // likely null
}
}Quick Quiz
Tip
Tip
Practice Garbage Collection Algorithms Tuning in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Garbage Collection - Algorithms & Tuning
Practice Task
Note
Practice Task - (1) Write a working example of Garbage Collection Algorithms Tuning from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Garbage Collection Algorithms Tuning is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Key Takeaways
- Garbage Collection automatically reclaims memory from objects no longer reachable.
- Minor GC - collects the Young Generation (Eden + Survivors). Very fast (milliseconds). Triggered when Eden is full.
- Major GC - collects the Old Generation. Slower (hundreds of ms). Triggered when Old Gen is low.
- Full GC - collects Young + Old + Metaspace. Very slow (seconds). Triggered by heap pressure.
Finished this lesson?