Autocoder

Java Garbage Collection Interview Questions

Last updated 2026-11-19

Garbage collection questions test whether you understand what happens to objects you stop referencing, and whether you can reason about pauses and memory leaks. Interviewers expect you to name the generations, explain reachability, compare the main collectors and list real leak patterns.

This page assumes a modern JDK where G1 is the default collector. The memory areas themselves are covered further on the JVM internals page.

Default collectorG1 since Java 9 on server-class machines
Low-latency collectorsZGC and Shenandoah
Java version17 and later, notes on 21

Vocabulary to use precisely

Java Garbage Collection Interview Questions: questions with worked answers

  1. 1

    How does Java decide that an object is garbage?

    easy

    An object is garbage when it is not reachable from any GC root through a chain of strong references. Roots include local variables and parameters on thread stacks, static fields, active threads, JNI references and loaded classes. Java does not use reference counting, so cyclic references (A points to B points to A) are collected as soon as the cycle is unreachable from roots.

  2. 2

    Explain the heap generations and the weak generational hypothesis.

    easy

    The hypothesis is that most objects die young. The heap is therefore split into a young generation (Eden and survivor spaces S0 and S1) and an old generation. New objects go to Eden; a minor GC copies live ones into a survivor space and increments their age; after reaching a tenuring threshold (at most 15) or when survivors overflow, they are promoted to the old generation. Collecting only the small young area is cheap and frequent.

  3. 3

    What is the difference between minor, major and full GC?

    medium

    A minor GC collects the young generation only and is usually short. A major GC collects the old generation. A full GC collects the whole heap and, depending on the collector, metaspace too, and is typically the longest pause. In G1 the terms map to young collections, mixed collections (young plus some old regions) and the fallback full GC, which signals trouble.

  4. 4

    Describe the basic GC algorithms: mark-sweep, mark-compact and copying.

    medium

    Mark-sweep marks reachable objects, then frees the unmarked ones, leaving fragmentation. Mark-compact additionally slides live objects together to remove fragmentation, at the cost of moving objects and updating references. Copying splits memory into two areas and copies live objects from one to the other, which is fast when most objects are dead, so it suits the young generation but needs spare space.

  5. 5

    Compare Serial, Parallel, G1, ZGC and Shenandoah.

    medium

    Serial uses one thread and suits tiny heaps or containers with one CPU. Parallel uses many threads to maximise throughput with longer pauses. G1 divides the heap into equal regions, collects the most garbage-rich ones first and aims for a pause target (default 200 ms). ZGC and Shenandoah do most work concurrently with the application, aiming for pauses of a few milliseconds regardless of heap size, trading some throughput and memory. ZGC gained a generational mode in Java 21 and made it the default in Java 23.

  6. 6

    How does G1 work?

    medium

    G1 splits the heap into roughly 2000 regions of 1 to 32 MB, each acting as Eden, survivor or old. Young collections evacuate live objects from Eden and survivor regions. A concurrent marking cycle starts when old occupancy passes a threshold (45 percent by default), then mixed collections reclaim old regions with the most garbage, within the MaxGCPauseMillis goal. Humongous objects, at least half a region in size, get dedicated contiguous regions and can cause fragmentation problems.

  7. 7

    Name the four reference types and a use for each.

    medium

    Strong references are ordinary and prevent collection. A SoftReference is cleared only when memory is short, which suits caches. A WeakReference is cleared at the next GC once only weakly reachable, as used by WeakHashMap and canonicalising maps. A PhantomReference never returns its referent and is enqueued after finalisation, used for cleanup actions together with a ReferenceQueue (Cleaner is built on it).

    java
    import java.lang.ref.*;
    Object o = new Object();
    WeakReference<Object> w = new WeakReference<>(o);
    o = null;
    System.gc();                    // a hint, not a guarantee
    System.out.println(w.get());    // usually null after the collection
  8. 8

    Can Java leak memory? Give common patterns.

    hard

    Yes, logically. The collector frees unreachable objects, but objects you keep reachable and never use are leaks. Typical causes: a static or long-lived collection that only grows, listeners or callbacks never deregistered, ThreadLocal values left in pooled threads, caches without an eviction policy, inner classes holding a reference to an outer instance, unclosed streams or connections, and mutable HashMap keys that cannot be removed. Diagnose with a heap dump and look at the dominator tree.

    java
    class Registry {
        static final List<byte[]> CACHE = new ArrayList<>();  // grows forever
        static void handle() { CACHE.add(new byte[1_000_000]); }
    }
  9. 9

    What does System.gc() do and is finalize reliable?

    medium

    System.gc() is a request; the JVM may run a full GC or ignore it (-XX:+DisableExplicitGC). Calling it in production code is a smell. finalize() has no timing guarantee, can resurrect objects, slows collection and is deprecated for removal since Java 18. Use try-with-resources for deterministic cleanup and Cleaner as a safety net.

  10. 10

    What kinds of OutOfMemoryError exist and what does each indicate?

    medium

    "Java heap space" means live data does not fit in the heap, or a leak. "GC overhead limit exceeded" means the JVM spent most of its time collecting while freeing almost nothing. "Metaspace" points to too many loaded classes, often from classloader leaks. "unable to create native thread" is an OS limit on threads or memory. "Requested array size exceeds VM limit" is a single huge allocation.

  11. 11

    Which JVM flags control the heap and the collector?

    easy

    -Xms sets the initial heap and -Xmx the maximum; setting them equal avoids resize pauses. -Xss sets the thread stack size. -XX:+UseG1GC, -XX:+UseParallelGC, -XX:+UseZGC and -XX:+UseSerialGC select the collector. -XX:MaxGCPauseMillis sets the G1 pause goal, -XX:MaxMetaspaceSize caps metaspace, and -Xlog:gc* writes unified GC logs. -XX:+HeapDumpOnOutOfMemoryError captures a dump on failure.

    java
    java -Xms2g -Xmx2g -XX:+UseG1GC -XX:MaxGCPauseMillis=100 -Xlog:gc*:file=gc.log MyApp
  12. 12

    What is a safepoint and why do GC pauses scale with something other than heap size?

    medium

    A safepoint is a point where every Java thread is at a known state so the JVM can do work such as a GC pause. Threads must reach it before the pause begins, so a long counted loop without a safepoint poll can delay everyone. Pause length depends on the amount of live data being copied or marked, the number of roots, and thread count, not on the total heap size alone, which is why concurrent collectors keep pauses short even on huge heaps.

  13. 13

    What is TLAB and escape analysis?

    medium

    A Thread Local Allocation Buffer gives each thread a private chunk of Eden so most allocations are a pointer bump with no locking. Escape analysis lets the JIT notice that an object never leaves a method; it can then allocate its fields in registers (scalar replacement) or elide locks, so some "new" calls cost nothing on the heap.

  14. 14

    How would you diagnose a production memory problem?

    medium

    Start by looking at the GC log for allocation rate, pause times and post-collection occupancy: a steadily rising floor after full collections means a leak. Capture a heap dump with jcmd GC.heap_dump, open it in a tool such as Eclipse MAT or VisualVM and read the dominator tree to find what retains the memory. Use Java Flight Recorder for allocation hotspots. Change flags only after measurement.

  15. 15

    What is WeakHashMap and when does it help?

    medium

    WeakHashMap holds its keys through weak references, so an entry disappears once nothing else references the key. It helps for metadata attached to objects you do not own. It misbehaves if the value strongly references the key, which keeps the entry alive forever, and it is a poor fit for general caches because eviction depends on GC timing, not usage.

Frequently asked questions

Which GC is default in Java 17?

G1, unless the machine has fewer than two CPUs or under about 1792 MB of memory, where the JVM picks Serial.

Can I force garbage collection?

Not reliably. System.gc() is only a request and should be avoided outside tests.

Does setting a variable to null free memory?

It makes the object eligible if no other reference exists, and rarely matters except for long-lived references such as fields or large arrays in long methods.

Is GC knowledge needed for freshers?

Basic generations, reachability and the OutOfMemoryError types are enough. Collector comparison is expected from experienced candidates; see Java interview questions.

Related guides

More in Programming Language Interview Questions by Language

See all in this section