Memory & GChigh

GC Algorithms: G1, ZGC, Shenandoah

Java ships with multiple GC implementations: Serial (single-thread), Parallel (throughput), G1 (balanced), ZGC (ultra-low latency), Shenandoah (low latency). The default since Java 9 is G1.

Memory anchor

G1 = a cleaning crew that tackles the messiest rooms first (Garbage-First). ZGC = a Roomba that cleans while you walk around -- you barely notice it (sub-ms pauses). Parallel GC = shutting down the whole house for a deep clean (max throughput, longest pause).

Expected depth

G1: region-based, concurrent marking phase (runs with app threads), evacuation (stop-the-world but bounded by pause-time target). -XX:MaxGCPauseMillis=200 is the target (not guarantee). Best for: multi-GB heaps, apps that need predictable pauses. ZGC (Java 15+, production-ready): concurrent relocation — almost all GC work runs concurrently, pauses are < 1ms regardless of heap size. Scales to multi-TB heaps. Best for: latency-critical apps with large heaps. Shenandoah (Red Hat, OpenJDK): similar concurrent relocation model to ZGC. Parallel GC: highest throughput (batch/offline processing), longest pauses.

Deep — senior internals

ZGC uses colored pointers (bits in the 64-bit pointer encode GC state — load barriers on every object read update the pointer). This enables concurrent relocation: the GC can move objects while the application runs, using load barriers to intercept reads and return the new location. Shenandoah uses Brooks forwarding pointers (an extra word per object). Both trade increased per-read overhead for pause reduction. G1's concurrent marking uses a tri-color invariant (white/grey/black) and write barriers (SATB — Snapshot At The Beginning) to handle objects modified during marking. Java 21's Generational ZGC adds generational collection to ZGC's concurrent model for better throughput.

🎤Interview-ready answer

G1 is the default GC — region-based with configurable pause targets, good for multi-GB heaps where you want predictable but not ultra-low pauses. ZGC (Java 15+) does nearly all work concurrently using colored pointers and load barriers, achieving sub-millisecond pauses at multi-TB heap sizes — use it for latency-critical services. Parallel GC maximizes throughput for batch workloads at the cost of longer stop-the-world pauses. Tune GC with -Xmx, -Xms, and -XX:MaxGCPauseMillis; monitor with GC logs (-Xlog:gc*).

Common trap

Setting -Xmx and -Xms to the same value prevents heap resizing (good for predictability) but means the JVM requests max memory from the OS immediately — in containerized environments this can trigger OOM kills if other processes share the host.