Garbage Collection in Java
Java's garbage collector automatically identifies and reclaims heap memory occupied by objects that are no longer reachable from any live thread or static ...
How the Garbage Collector Works
Java's garbage collector automatically identifies and reclaims heap memory occupied by objects that are no longer reachable from any live thread or static reference. This frees developers from manual memory management but requires understanding how the GC determines what is garbage and what strategies it uses to reclaim memory efficiently.
The root set is the starting point for reachability analysis. It consists of local variables on all thread stacks, static fields of loaded classes, and JNI references. The garbage collector traces all references from these roots through the object graph. Any object that cannot be reached by following references from the root set is considered garbage and is eligible for reclamation.
Mark-and-sweep is the conceptual foundation of most GC algorithms. In the mark phase, the collector traverses all reachable objects and marks them as live. In the sweep phase, it reclaims the memory of all unmarked objects. Modern collectors add a compaction phase that moves live objects together to eliminate fragmentation, making future allocations faster.
The generational hypothesis states that most objects die young. Java GCs exploit this by dividing the heap into young and old generations. New objects are allocated in Eden. Minor GCs collect Eden and the two survivor spaces, which alternate between holding objects that survived previous minor collections. Objects that survive enough minor collections are promoted to the old generation, collected during major GCs.
Stop-the-world pauses are periods when all application threads are suspended so the GC can perform work safely. While modern collectors minimize these pauses through concurrent marking and incremental collection, understanding that they exist helps explain latency spikes in Java applications under memory pressure.
Example to observe GC behavior:
System.gc(); // hints to the JVM to run GC (not guaranteed) Runtime rt = Runtime.getRuntime(); System.out.println("Free: " + rt.freeMemory());
Interview tip: Explain what happens if an object overrides finalize(). The GC adds it to a finalization queue before reclaiming it, which can delay collection by at least one GC cycle. Finalization is deprecated in modern Java because it is unpredictable and slow; use try-with-resources or Cleaner instead.
GC Algorithms: G1, ZGC, and Shenandoah
Java offers multiple garbage collection algorithms that make different trade-offs between throughput, latency, and memory footprint. Choosing the right collector for your application profile can dramatically improve performance. The three most relevant modern collectors are G1 GC, ZGC, and Shenandoah.
G1 GC (Garbage First) became the default collector in Java 9. It divides the heap into equal-sized regions rather than strict young and old areas. During a collection, it prioritizes regions with the most garbage first, hence the name. G1 targets a user-configurable maximum pause time with -XX:MaxGCPauseMillis, making it suitable for applications that need predictable, sub-second pauses. It performs well on heaps from 4 GB to 32 GB.
ZGC was introduced in Java 11 as an experimental feature and made production-ready in Java 15. Its defining characteristic is near-constant pause times that remain below 10 milliseconds even on multi-terabyte heaps. ZGC performs most of its work concurrently with the application running, using colored pointers and load barriers to track object references during concurrent relocation. Enable it with -XX:+UseZGC.
Shenandoah, developed by Red Hat and available in OpenJDK, takes a similar approach to ZGC, also targeting low and consistent pause times. Its key distinction is that it performs concurrent compaction, moving live objects while the application runs and updating references atomically. Shenandoah is particularly effective for latency-critical applications. Enable it with -XX:+UseShenandoahGC.
For maximum throughput at the cost of longer pauses, the Parallel GC (-XX:+UseParallelGC) uses multiple threads to perform both minor and major collections, making the best use of available CPU cores during GC pauses. It is the best choice for batch processing jobs that prioritize total throughput over response time.
Selecting a collector:
# Low latency (microservices, APIs): ZGC or Shenandoah # Balanced (most web apps): G1 GC # Max throughput (batch jobs): Parallel GC
Interview tip: When asked which GC to choose, frame your answer around the application's latency requirements and heap size. G1 is the safe default; ZGC or Shenandoah are for applications where tail latency matters and pause times must be in single-digit milliseconds.
Memory Leaks and Common GC Problems
Even with automatic garbage collection, Java applications can suffer from memory leaks. A Java memory leak occurs when objects remain reachable through references even though they will never be used again. The garbage collector cannot reclaim reachable objects, so memory accumulates over time until the application crashes with OutOfMemoryError.
Static collections are a frequent source of leaks. A static HashMap that caches objects keeps those objects alive for the lifetime of the class. If the cache grows unboundedly, it eventually consumes all available heap. Use WeakHashMap instead when the cached data should be discarded when it is no longer referenced anywhere else, or implement an explicit size limit with eviction.
Listeners and callbacks are another common leak vector. If you add event listeners to a source but never remove them when the listener is no longer needed, the source holds a reference to the listener, keeping the listener's entire object graph alive. Always pair listener registration with deregistration, particularly in GUI frameworks and application containers.
Thread-local variables in thread pools are a subtle leak. If a thread-local variable is set by a task and never cleared, it persists on the thread because pooled threads are never destroyed. The next task that runs on the same thread inherits the stale value. Always call ThreadLocal.remove() at the end of a task.
Tools for detecting memory leaks include Java heap profilers such as Eclipse Memory Analyzer (MAT), JVisualVM, and YourKit. A heap dump is a snapshot of all objects on the heap at a point in time. Analyzing a heap dump reveals which objects are consuming the most memory and what reference chain is keeping them alive.
Example of a guarded cache with WeakHashMap:
Map<Key, Value> cache = Collections.synchronizedMap(new WeakHashMap<>()); cache.put(key, value); // value is GCed when key has no strong references
OutOfMemoryError has several subtypes: Java heap space (heap exhausted), GC overhead limit exceeded (too much time spent in GC with too little reclaimed), and Metaspace (class metadata exhausted). Each points to a different root cause and requires a different fix.
Interview tip: Describe how to investigate an OutOfMemoryError in production. The answer should cover enabling heap dumps on OOM with -XX:+HeapDumpOnOutOfMemoryError, capturing the dump, and using MAT to find the dominator tree, which shows which objects retain the most memory.