Java

Chapter 136: Garbage Collection in Java — Pauses, Collectors G1 ZGC, and Practical Tuning Mindset

Understand Java garbage collection: unreachable object reclamation, stop-the-world pauses, G1 as default collector, ZGC Shenandoah for low latency goals, and logs versus guessing with flags.

Author: Sushil Kumar

Java garbage collection tutorialJava G1 GCJava ZGC low latencyJava GC pause tuningJava GC logs Xlog

Chapter 136: Garbage Collection in Java

Garbage collection reclaims heap objects unreachable from GC roots (stack references, static fields, JNI, active threads). Collectors trade throughput, pause times, and memory overhead differently—JDK defaults evolved from ParallelG1 on server-class machines.


1. Topic title

GC: automatic memory recycling with collector-specific pause and footprint trade-offs


2. What it means

Young collections clear short-lived garbage cheaply; old collections compact long-lived graphs—algorithms differ (mark-sweep-compact, regional G1, concurrent ZGC).

System.gc() is a hintproduction code rarely calls it; tests sometimes @Disabled.

Logs-Xlog:gc*:file=gc.log:time,uptime,level,tags (flag shape varies by JDK) turn mystery stutters into timelines.


3. Why it is used

Developer productivitymanual free errors vanish at the cost of pause awareness.

Elastic servicesright-size heap + collector with SLO-driven evidence, not folklore.


4. Mental sketch

GC is roomba cleaning while you still walk on the rug—sometimes it pauses to lift chairs (stop-the-world phases). Different models bump furniture less often but may use more battery (CPU overhead).


5. Java code example

public class GcHintDemo {
    public static void main(String[] args) {
        for (int i = 0; i < 5_000_000; i++) {
            new Object();
        }
        System.out.println("allocated short-lived garbage");
    }
}

Short-lived allocations usually die in young GCwatch logs, not println, for real behavior.


6. Explanation of code

Escape analysis may scalar replace tiny objectsmicrobenchmarks lie without -prof gc.


7. Common mistakes

Giant heaps to “fixmemory leaksGC pauses grow; fix retained references.

Tuning without metrics-XX:+AlwaysPreTouch and friends have costsmeasure.


8. Best practices

Set container memory limits above Xmx + non-heap headroom explicitly—OOMKilled vs Java heap space diagnose differently.

Upgrade JDK for collector improvements before heroic flags.


9. Small practice task

Enable GC logging on a sample app and mark young vs old events during a warm-up loadcorrelate with p99 latency.


Beginner tip

If latency spikes align with GC logs on the same second, you found a suspectnot proof until CPU, locks, and I/O are ruled out too.