Prev Next

Java / Java 17 Garbage Collection Interview Questions

1. What is garbage collection in Java? 2. What is the purpose of a garbage collector in the JVM? 3. What are the types of garbage collectors available in Java 17? 4. What is the default garbage collector in Java 17? 5. What is the young generation in the JVM heap? 6. What is the old (tenured) generation in the JVM heap? 7. What is Metaspace in Java 17? 8. What is a minor GC? 9. What is a major GC? 10. What is a full GC? 11. Define a stop-the-world pause? 12. What is the Eden space? 13. What are Survivor spaces used for? 14. How do you enable GC logging in Java 17? 15. What is the purpose of the -Xmx and -Xms flags? 16. Why is G1 GC the default collector since Java 9? 17. How does G1 GC divide the heap into regions? 18. What is a humongous object in G1 GC? 19. How does G1 GC decide which regions to collect first? 20. What is a remembered set in G1 GC? 21. What is a card table and how does it help garbage collection? 22. How do you configure G1 GC's pause time goal? 23. What is the difference between G1 GC and Parallel GC? 24. When should you choose ZGC over G1 GC? 25. When should you choose Shenandoah over G1 GC? 26. What happens during a G1 GC mixed collection? 27. Why doesn't Java 17 include the CMS garbage collector? 28. How is Parallel GC different from Serial GC? 29. What is the difference between throughput and low-latency garbage collectors? 30. How do you troubleshoot frequent full GCs in a Java 17 application? 31. What is string deduplication in G1 GC? 32. How does the JVM decide when to trigger a GC cycle? 33. What is promotion in the context of generational garbage collection? 34. Why should you avoid explicit calls to System.gc()? 35. What is the difference between soft, weak, and phantom references? 36. Explain the internal working of G1 GC's concurrent marking cycle? 37. Explain the execution flow of a ZGC collection cycle? 38. How does ZGC achieve sub-millisecond pause times using colored pointers? 39. Explain the lifecycle of an object through the JVM heap under G1 GC? 40. How does Shenandoah's Brooks pointer (forwarding pointer) enable concurrent compaction? 41. What is an evacuation failure in G1 GC and how do you handle it? 42. How does garbage collection behave differently in a containerized environment with cgroup memory limits? 43. How can you optimize G1 GC for large heaps (32GB+)? 44. Explain the tricolor marking algorithm used in concurrent garbage collectors? 45. What are write barriers and load barriers, and how do collectors use them? 46. How do you analyze a GC log to identify a memory leak? 47. What is the difference between G1 GC's young-only phase and space-reclamation phase? 48. How does adaptive sizing (ergonomics) work in the JVM's garbage collectors? 49. Explain how class unloading interacts with garbage collection and Metaspace? 50. Which is better for a low-latency trading application - ZGC or Shenandoah - and why?

1. What is garbage collection in Java?

Garbage collection (GC) is the JVM's automatic process for reclaiming heap memory occupied by objects that are no longer reachable from any active part of the running program. Instead of the developer explicitly freeing memory (as in C's free() or C++'s delete ), the JVM periodically runs a backg...

Read full answer

2. What is the purpose of a garbage collector in the JVM?

The garbage collector exists to guarantee memory safety without requiring the developer to manually track object lifetimes. Specifically, it eliminates dangling-pointer and use-after-free bugs by only reclaiming objects once nothing can reach them, it prevents unbounded memory growth (and eventua...

Read full answer

3. What are the types of garbage collectors available in Java 17?

Java 17 ships with five usable collectors, plus one purely diagnostic collector, each selected with its own JVM flag: Collector Flag Best suited for Serial GC -XX:+UseSerialGC Small heaps, single-core machines Parallel GC -XX:+UseParallelGC Batch jobs prioritizing raw throughput G1 GC -XX:+UseG1G...

Read full answer

4. What is the default garbage collector in Java 17?

G1 (Garbage-First) GC is the default collector in Java 17, a role it has held since it replaced Parallel GC as the default in JDK 9 (JEP 248). G1 divides the heap into many equal-sized regions rather than fixed contiguous generations, which lets it collect only the regions holding the most garbag...

Read full answer

5. What is the young generation in the JVM heap?

The young generation is the portion of the heap where all new objects are first allocated, made up of one Eden space and two Survivor spaces (S0 and S1). It exists because of the weak generational hypothesis : most objects die shortly after creation, so concentrating collection effort on a small,...

Read full answer

6. What is the old (tenured) generation in the JVM heap?

The old generation holds objects that have survived enough minor GC cycles to be promoted out of the young generation - typically long-lived caches, singletons, and other data that outlives many request or task lifecycles. Because it usually makes up the bulk of the heap and tends to hold a much ...

Read full answer

7. What is Metaspace in Java 17?

Metaspace is the native (off-heap) memory region that stores class metadata - method bytecode, constant pools, field and method descriptors - for every loaded class. It replaced the old PermGen starting in Java 8. Unlike PermGen, which had a fixed maximum size carved out of the JVM's own memory, ...

Read full answer

8. What is a minor GC?

A minor GC is a collection that runs against the young generation only - it scans Eden and the active survivor space, copies still-reachable objects into the other survivor space (or promotes them to old gen if they're old enough), and reclaims everything else. It's triggered whenever Eden fills ...

Read full answer

9. What is a major GC?

"Major GC" is used, somewhat loosely, to describe a collection that reclaims the old generation . Its exact meaning depends on the collector: for Parallel or Serial GC it's a distinct stop-the-world old-gen collection; for G1 there's no single "major GC" event as such - instead, a concurrent mark...

Read full answer

10. What is a full GC?

A full GC collects the entire heap - young generation, old generation, and typically triggers a Metaspace cleanup pass too - in one operation, and in most collectors it's a fully stop-the-world, single-threaded compaction. It's the most expensive kind of collection the JVM can run, so it's normal...

Read full answer

11. Define a stop-the-world pause?

A stop-the-world (STW) pause is a period during which the JVM suspends every application ("mutator") thread at a safepoint so the garbage collector can safely inspect and move objects without the program changing references out from under it. STW pauses are necessary because moving or relocating ...

Read full answer

12. What is the Eden space?

Eden is the sub-region of the young generation where nearly all new objects are first allocated, typically via a per-thread Thread-Local Allocation Buffer (TLAB) so most allocations avoid any locking or contention with other threads. Because most objects die quickly, Eden fills up rapidly and is ...

Read full answer

13. What are Survivor spaces used for?

The two survivor spaces, S0 and S1, hold objects that have survived at least one minor GC but haven't yet been promoted to the old generation. Only one of the two is "active" (in use) at any given time; the other stays empty until the next collection. During each minor GC, live objects are copied...

Read full answer

14. How do you enable GC logging in Java 17?

Java 17 uses the unified JVM logging framework (introduced in JDK 9) via the -Xlog flag, which replaced the older per-collector flags like -XX:+PrintGCDetails . A typical production-ready configuration looks like: -Xlog:gc*:file=gc.log:time,uptime,level,tags:filecount=5,filesize=20M Here, gc* sel...

Read full answer

15. What is the purpose of the -Xmx and -Xms flags?

-Xmx sets the maximum heap size the JVM is allowed to grow to, and -Xms sets the initial heap size allocated at startup - for example, -Xms512m -Xmx4g starts with a 512MB heap and allows growth up to 4GB. If left unset, the JVM's ergonomics pick defaults based on available memory (or, inside a co...

Read full answer

16. Why is G1 GC the default collector since Java 9?

G1 replaced Parallel GC as the default in JDK 9 (JEP 248) because it offers a better all-around balance for the majority of modern workloads without requiring heavy manual tuning. Its region-based heap layout lets it collect only the regions with the most reclaimable garbage first rather than bei...

Read full answer

17. How does G1 GC divide the heap into regions?

G1 splits the heap into many equal-sized regions, sized as a power of two between 1MB and 32MB, chosen automatically based on heap size (targeting roughly 2048 regions total) or overridden explicitly with -XX:G1HeapRegionSize . Unlike the fixed, contiguous young/old layout used by Parallel or Ser...

Read full answer

18. What is a humongous object in G1 GC?

A humongous object is any object at least 50% the size of a single G1 region - large arrays are the most common example. Rather than being allocated normally into Eden, it's placed directly into one or more contiguous humongous regions reserved just for it. This special-cases large allocations be...

Read full answer

19. How does G1 GC decide which regions to collect first?

This is the origin of G1's name - "Garbage First". During its concurrent marking cycle, G1 tracks how much live versus garbage data each old region holds, then, for every subsequent collection pause, it picks the set of regions offering the most reclaimable garbage for the amount of pause time it...

Read full answer

20. What is a remembered set in G1 GC?

A remembered set (RSet) is a per-region data structure that tracks which other regions contain references pointing into that region. Because G1 can collect a single region without scanning the whole heap, it needs a fast way to find all the inbound references to that region from elsewhere - the R...

Read full answer

21. What is a card table and how does it help garbage collection?

A card table divides the heap into small, fixed-size chunks called cards (512 bytes each). Whenever application code writes a reference field, a JIT-inserted write barrier marks the corresponding card as "dirty" in a compact byte array. During a young collection, the GC needs to find old-to-young...

Read full answer

22. How do you configure G1 GC's pause time goal?

The pause-time goal is set with -XX:MaxGCPauseMillis= , for example -XX:MaxGCPauseMillis=100 to ask G1 to try to keep pauses at or under 100ms. The default is 200ms. It's important to understand this is a soft goal , not a hard guarantee - G1 uses it to decide how many regions to include in ea...

Read full answer

23. What is the difference between G1 GC and Parallel GC?

Both use multiple threads and are generational, but they optimize for different goals and use very different heap layouts. Aspect G1 GC Parallel GC Heap layout Many equal-sized regions Fixed contiguous young/old generations Primary goal Configurable, predictable pause times Maximum throughput Old...

Read full answer

24. When should you choose ZGC over G1 GC?

ZGC is the better choice when pause time matters more than raw throughput and the heap is large - it keeps stop-the-world pauses limited to brief root-scanning steps, typically well under 10ms, regardless of whether the heap is 8GB or several terabytes, because marking and relocation happen concu...

Read full answer

25. When should you choose Shenandoah over G1 GC?

Shenandoah targets the same goal as ZGC - pause times that don't scale with heap size - but reaches it through a different mechanism: concurrent compaction using per-object forwarding (Brooks) pointers rather than colored pointers and load barriers on every reference read. It's a strong choice wh...

Read full answer

26. What happens during a G1 GC mixed collection?

Once G1's concurrent marking cycle finishes identifying which old regions hold the most garbage, G1 enters a mixed collection phase: subsequent evacuation pauses combine the usual young regions with a handful of the highest-garbage old regions selected during marking, copying their live objects o...

Read full answer

27. Why doesn't Java 17 include the CMS garbage collector?

CMS (Concurrent Mark Sweep) was formally deprecated in JDK 9 (JEP 291) and removed entirely in JDK 14 (JEP 363), so it was already gone well before Java 17. The main reasons were fragmentation and maintenance cost: CMS did not compact the old generation as part of its normal cycle, so long-runnin...

Read full answer

28. How is Parallel GC different from Serial GC?

Both are fully stop-the-world, compacting collectors with no concurrent phases, but they differ in threading: Serial GC uses a single thread for every collection (young and old), while Parallel GC uses multiple threads for both. Serial GC's single-threaded design makes sense for small heaps or si...

Read full answer

29. What is the difference between throughput and low-latency garbage collectors?

Throughput-oriented collectors aim to maximize the percentage of total time spent running application code versus doing GC work, generally by batching up collection work and accepting longer, less frequent pauses. Low-latency collectors instead aim to minimize the length of any individual pause, ...

Read full answer

30. How do you troubleshoot frequent full GCs in a Java 17 application?

Start by enabling GC logging ( -Xlog:gc*:file=gc.log:time,uptime,level,tags ) if it isn't already on, and look at what's triggering each full GC - the log will show whether it's an evacuation failure, Metaspace pressure, or an explicit System.gc() call. Next, plot old-generation occupancy over ti...

Read full answer

31. What is string deduplication in G1 GC?

String deduplication, enabled with -XX:+UseStringDeduplication , is a G1-specific optimization that finds String objects with identical backing character arrays and makes them share a single copy of that array in memory. String objects themselves remain fully immutable and distinct - only the und...

Read full answer

32. How does the JVM decide when to trigger a GC cycle?

The trigger differs by generation and collector. A minor GC fires whenever a thread can't satisfy a new allocation from Eden - there's simply no space left in the young generation's active area. For G1's concurrent marking cycle , the trigger is based on -XX:InitiatingHeapOccupancyPercent (IHOP, ...

Read full answer

33. What is promotion in the context of generational garbage collection?

Promotion is the act of moving an object out of the young generation into the old generation because it has proven itself long-lived rather than a typical short-lived object. Concretely, each time an object survives a minor GC it's copied to a survivor space and its age counter increments; once t...

Read full answer

34. Why should you avoid explicit calls to System.gc()?

System.gc() is only a request , not a command - the JVM is free to ignore it - but by default most collectors treat it as a signal to run a full, stop-the-world garbage collection, which is the most expensive kind of collection available. Calling it from application code removes control from the ...

Read full answer

35. What is the difference between soft, weak, and phantom references?

Beyond ordinary strong references, Java's java.lang.ref package offers three progressively weaker reference types that change how eagerly the GC reclaims the referent. Type Cleared Typical use SoftReference Only right before an OutOfMemoryError Memory-sensitive caches WeakReference At the next GC...

Read full answer

36. Explain the internal working of G1 GC's concurrent marking cycle?

G1's concurrent marking cycle identifies which old regions hold the most garbage so later mixed collections know what to reclaim. It runs in several distinct phases, most of them alongside the running application: flowchart LR A[Initial Mark - STW, piggybacked on a young GC] --> B[Root Region Sca...

Read full answer

37. Explain the execution flow of a ZGC collection cycle?

ZGC's cycle alternates brief stop-the-world pauses with much longer concurrent phases, keeping every pause's cost tied to the number of GC roots rather than the size of the live heap: flowchart LR A[Pause Mark Start - STW, scan roots] --> B[Concurrent Mark - load barriers self-heal refs while tra...

Read full answer

38. How does ZGC achieve sub-millisecond pause times using colored pointers?

ZGC repurposes unused bits within each 64-bit object reference to store metadata directly in the pointer itself - bits indicating things like marked0 , marked1 , remapped , and finalizable state. This is what's meant by a "colored" pointer: the color of a reference tells the runtime, at the momen...

Read full answer

39. Explain the lifecycle of an object through the JVM heap under G1 GC?

An object's journey through the heap follows a predictable path shaped by the generational hypothesis, with G1's region-based layout determining exactly where each step physically happens: flowchart TD A[Allocated in Eden region via TLAB] --> B{Reachable at next minor GC?} B -- No --> Z[Reclaimed...

Read full answer

40. How does Shenandoah's Brooks pointer (forwarding pointer) enable concurrent compaction?

Every object managed by Shenandoah carries one extra native-word field - the Brooks pointer - that normally points to itself. When the collector decides to evacuate an object (copy it to a new region as part of compaction), it first creates the copy, then atomically compare-and-swaps the original...

Read full answer

41. What is an evacuation failure in G1 GC and how do you handle it?

An evacuation failure (sometimes logged as "to-space exhausted") happens when G1 starts copying live objects out of the regions it's collecting but runs out of free regions to copy them into partway through the pause. Because objects can't simply be left half-copied, G1 has to fall back to a safe...

Read full answer

42. How does garbage collection behave differently in a containerized environment with cgroup memory limits?

Since JDK 10 (JEP 343, container awareness, refined through JDK 17), the JVM reads cgroup limits rather than the host machine's total physical resources when computing default ergonomics - both the number of "available processors" (which drives GC thread counts) and the memory limit used for defa...

Read full answer

43. How can you optimize G1 GC for large heaps (32GB+)?

Large heaps stress the defaults G1 tunes itself for, so a few adjustments tend to pay off: -XX:G1HeapRegionSize=32m -XX:InitiatingHeapOccupancyPercent=30 -XX:ConcGCThreads=8 -XX:G1ReservePercent=15 -XX:+UseNUMA Explicitly setting a larger region size (up to the 32MB cap) reduces the total region ...

Read full answer

44. Explain the tricolor marking algorithm used in concurrent garbage collectors?

Tricolor marking is the bookkeeping scheme concurrent collectors use to track marking progress while the application keeps mutating references at the same time. Every object is conceptually one of three colors at any point during the marking phase: Color Meaning White Not yet visited - candidate ...

Read full answer

45. What are write barriers and load barriers, and how do collectors use them?

Both are small pieces of code the JIT compiler automatically inserts around reference field accesses, but they intercept different operations and serve different collector designs. A write barrier runs after a reference field is written . G1 uses one to mark the card table dirty for cross-region ...

Read full answer

46. How do you analyze a GC log to identify a memory leak?

Start by enabling detailed unified logging if it isn't already active: -Xlog:gc*:file=gc.log:time,uptime,level,tags Load the resulting log into a visualization tool such as GCEasy or GCViewer and focus on old-generation occupancy immediately after each full or major collection - that's the closes...

Read full answer

47. What is the difference between G1 GC's young-only phase and space-reclamation phase?

G1 alternates between two operating phases over its lifetime. During the young-only phase , every evacuation pause collects only young-generation regions (Eden and survivors) - no old regions are touched - occasionally piggybacking an Initial Mark onto one of these pauses once old-gen occupancy c...

Read full answer

48. How does adaptive sizing (ergonomics) work in the JVM's garbage collectors?

Adaptive sizing lets the JVM automatically tune heap-region sizing at runtime instead of relying on fixed, hand-picked values - it's controlled by -XX:+UseAdaptiveSizePolicy , which is enabled by default for Parallel GC. Under Parallel GC, the policy runs a feedback loop: after each collection it...

Read full answer

49. Explain how class unloading interacts with garbage collection and Metaspace?

Class metadata - bytecode, constant pools, method and field descriptors - lives in Metaspace, and a class can only be unloaded, freeing its slice of Metaspace, once the ClassLoader that defined it becomes completely unreachable: no live instances of any class it loaded, and no remaining reference...

Read full answer

50. Which is better for a low-latency trading application - ZGC or Shenandoah - and why?

Both target the same outcome - pause times that stay low and roughly constant regardless of heap size - which is exactly what a latency-sensitive trading system needs, but they get there through different mechanisms with different overhead profiles. Aspect ZGC Shenandoah Mechanism Colored pointer...

Read full answer

«
»

Comments & Discussions