# Garbage Collection Basics and GC Roots

> How does garbage collection work in Java? What are GC roots, generations, and the common collectors like G1 and ZGC?

Canonical: https://www.internhack.in/learn/interview/java-interview/java-garbage-collection-basics
Last updated: 2026-11-28

Difficulty: Advanced

## Question

How does garbage collection work in Java? What are GC roots, generations, and the common collectors like G1 and ZGC?

## Answer

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.

## Code examples

### Weak reference and reachability

```
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.

### A leak through a static collection

```
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.

## Key points

- Objects are garbage when unreachable from GC roots; cycles are not a problem.
- GC roots: thread stacks, static fields, active threads and JNI references.
- Generational heap: Eden, survivor spaces and old generation; minor GC is cheap, full GC is expensive.
- G1 is the default since Java 9; ZGC and Shenandoah target very low pause times.
- System.gc() is only a hint; leaks in Java mean unwanted but still reachable objects.

## Common follow-up questions

- What is a stop-the-world pause?
- How would you find a memory leak in production?
- Difference between soft, weak and phantom references?
- Why is G1 called region-based?

## Interview tips

- Define garbage as unreachable from GC roots. It immediately shows you understand it is not reference counting.
- When asked whether Java has leaks, answer yes and give the static collection example.

## Concepts covered

Garbage Collection, GC Roots, Generational GC, Reachability, G1

Previous: [JVM Memory: Heap, Stack, Metaspace](https://www.internhack.in/learn/interview/java-interview/java-jvm-memory-model) · Next: [Thread vs Runnable and the Thread Lifecycle](https://www.internhack.in/learn/interview/java-interview/java-thread-vs-runnable) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [synchronized vs volatile: Visibility, Atomicity and Ordering](https://www.internhack.in/learn/interview/java-interview/java-synchronized-volatile)
- [wait(), notify() and the Producer-Consumer Pattern](https://www.internhack.in/learn/interview/java-interview/java-wait-notify)
- [Deadlock: Conditions, Detection and Prevention](https://www.internhack.in/learn/interview/java-interview/java-deadlock)
- [ExecutorService, Thread Pools and Future](https://www.internhack.in/learn/interview/java-interview/java-executorservice-thread-pools)
- [Lambdas, Functional Interfaces and Method References](https://www.internhack.in/learn/interview/java-interview/java-lambdas-functional-interfaces)
- [Streams API: Pipelines, Laziness and Collectors](https://www.internhack.in/learn/interview/java-interview/java-streams-api)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
