KatInterview

How the JVM Allocates and Reclaims Memory Without Manual Freeing

System DesignModel answer
MediumModel answerSystem Designjavajvmgarbage-collection

Last updated

Walk through how the JVM places objects in memory, decides which are dead, reclaims them with different collectors, and why leaks and resource problems still occur.

Java programmers never call free, yet long-running services do not normally run out of memory. Explain how this works.

Prepare a structured answer, as if speaking to a reviewer who cannot interrupt you with questions. It should cover:

  1. Where the JVM keeps different kinds of data, and how objects get allocated.
  2. How the JVM decides an object is no longer needed.
  3. How the memory is actually reclaimed, including generational collection and the main trade-offs between the common collectors.
  4. What automatic memory management does not protect you from, and how you would diagnose problems.

State any assumptions you make, such as a modern HotSpot JVM, and mention where behavior differs between collectors.

Hints

Hint 1

Start by separating the memory areas (heap, thread stacks, metaspace) and say what lives where, before you talk about collection.

Hint 2

Define garbage by reachability from GC roots, not by reference counting. Use that to explain why cycles of dead objects are still collected.

Hint 3

Organize the collector discussion around three goals: throughput, pause latency and footprint. Then place Parallel, G1, ZGC and Shenandoah on that map.

Hint 4

Finish with what the GC cannot do: lingering references that keep objects reachable, unclosed non-memory resources, and the different causes of OutOfMemoryError.