Difficulty: Advanced
How does garbage collection work in Java? What are GC roots, generations, and the common collectors like G1 and ZGC?
In C and C++ you free memory yourself and pay for mistakes with crashes and leaks. Java hands that responsibility to the garbage collector, and interviewers want to know you understand what it does, when it runs and what it can't save you from.
The core principle is reachability, not reference counting. An object is garbage if the program can no longer reach it by following references starting from a set of GC roots. GC roots are the fixed starting points of the search: local variables and parameters on the stacks of live threads, static fields of loaded classes, active threads themselves, JNI references, and monitors held by synchronization. The collector marks everything reachable from these roots; anything unmarked is eligible for collection. This is why circular references, where A points to B and B points to A, are not a problem in Java: if neither is reachable from a root, both are collected. Reference counting would leak them.
Next, the generational hypothesis: most objects die young. So the heap is split into a young generation and an old generation. New objects go to Eden. When Eden fills, a minor GC runs: live objects are copied to a survivor space, and dead ones are dropped. Objects surviving several minor GCs (the tenuring threshold) are promoted to the old generation. When the old generation fills, a major or full GC runs, which is far more expensive. Young collections use a copying algorithm which is fast and leaves no fragmentation. Old generation collectors often use mark-sweep-compact to also remove fragmentation.
Pause behaviour matters. Most collectors stop all application threads for parts of their work; this is called a stop-the-world pause. Modern collectors try to shrink or avoid these pauses.
The main collectors you should name: Serial (single-threaded, small heaps and simple apps), Parallel (multi-threaded, focused on throughput; the default up to Java 8), G1 (default since Java 9; divides the heap into many equal regions, collects the regions with the most garbage first, and aims for a pause-time target set by -XX:MaxGCPauseMillis), ZGC and Shenandoah (concurrent, compacting collectors aiming for pauses of a few milliseconds even on very large heaps; ZGC became production-ready in Java 15, and generational ZGC arrived in Java 21). The old CMS was removed in Java 14.
Points that come up often. System.gc() is only a hint; the JVM may ignore it, and calling it in production code is a smell. Since finalize is deprecated, use try-with-resources or Cleaner. Java has four reference strengths: strong (normal), soft (cleared when memory is low, used for caches), weak (cleared at the next GC, used in WeakHashMap) and phantom (for post-mortem cleanup).
Can Java have memory leaks? Yes, when objects are still reachable but no longer needed: static collections that only grow, unclosed listeners, ThreadLocal values in thread pools, and caches without eviction. GC frees unreachable objects, not unused-but-reachable ones. To investigate, take a heap dump and look at the dominator tree, and enable GC logging with -Xlog:gc.
import java.lang.ref.WeakReference;
public class GcDemo {
public static void main(String[] args) {
Object strong = new Object();
WeakReference<Object> weak = new WeakReference<>(strong);
System.out.println(weak.get() != null);
strong = null;
System.gc();
System.out.println(weak.get() == null);
}
}
After the only strong reference is cleared, the object is reachable only through a weak reference, so a collection clears it. The second line is what HotSpot typically prints, but System.gc() is only a hint and the result is not guaranteed by the language.
import java.util.*;
public class LeakDemo {
private static final List<byte[]> CACHE = new ArrayList<>();
static void handleRequest() {
CACHE.add(new byte[1024 * 1024]);
}
}
// Everything in CACHE is reachable from a static field (a GC root),
// so it is never collected: repeated calls end in OutOfMemoryError.
The objects are reachable from a GC root, so the collector must keep them even if the program never reads them again.
Garbage Collection, GC Roots, Generational GC, Reachability, G1