How the JVM Allocates and Reclaims Memory Without Manual Freeing
System DesignModel answerLast 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:
- Where the JVM keeps different kinds of data, and how objects get allocated.
- How the JVM decides an object is no longer needed.
- How the memory is actually reclaimed, including generational collection and the main trade-offs between the common collectors.
- 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
I assume a recent HotSpot JVM (17 or later), where G1 is the default collector. I will explain the general model first and then compare collectors.
1. Where data lives and how allocation works
- Heap: all objects and arrays, shared by every thread. This is the area the garbage collector manages.
- Thread stacks: one per thread, holding stack frames with local variables, primitives and references to heap objects. Frames are popped automatically when a method returns, so no GC is needed here.
- Metaspace: class metadata (in native memory since Java 8). It is reclaimed when classes are unloaded, typically when their classloader becomes unreachable.
- Other native memory: JIT code cache, direct
ByteBuffers, thread stacks themselves and GC bookkeeping. These sit outside the heap limit (-Xmx).
Allocation is cheap. Each thread gets a thread-local allocation buffer (TLAB) in the young generation, so creating an object is mostly a pointer bump with no locking. When the TLAB or young space fills, the JVM triggers a collection.
2. What counts as garbage: reachability
The JVM does not count references. It starts from GC roots and traces everything reachable:
- local variables and parameters on live thread stacks,
- static fields of loaded classes,
- active threads and JNI references,
- other internal roots such as monitors in use.
Any object not reachable from a root is garbage. A consequence is that cycles are not a problem: two objects pointing at each other but unreachable from any root are both collected. This is the key advantage over naive reference counting.
Java also has weaker reference types (SoftReference, WeakReference, PhantomReference) that let a cache or listener registry refer to an object without keeping it alive. Finalizers are deprecated; use Cleaner or try-with-resources instead.
3. How reclamation works
Basic algorithms
- Mark-sweep: mark reachable objects, sweep the rest. Leaves fragmentation.
- Mark-compact: also slides survivors together, removing fragmentation at the cost of moving objects and updating references.
- Copying: copy live objects to a fresh region and discard the old one wholesale. Cost is proportional to live data, not garbage, which is ideal when most objects die.
Generational hypothesis: most objects die young. So the heap is split:
- Young generation (eden plus two survivor spaces): collected frequently with a copying collector. Survivors are copied between survivor spaces and promoted after surviving a number of collections.
- Old generation: long-lived objects, collected less often with mark-compact or concurrent marking.
Minor collections only trace the young generation. To do that without scanning the old generation, the JVM uses card tables / remembered sets and write barriers to track old-to-young references.
Stop-the-world vs concurrent: at safepoints, application threads pause. Collectors differ in how much work happens while the application keeps running.
4. Collector trade-offs
| Collector | Strength | Cost |
|---|---|---|
| Serial | Tiny footprint, simple; fine for small heaps or containers with one core | Long pauses on larger heaps |
| Parallel | Highest throughput for batch jobs | Pauses grow with heap size |
| G1 (default) | Region-based, aims at a pause target (-XX:MaxGCPauseMillis), balanced | More overhead than Parallel, can have long mixed collections or full GC fallback |
| ZGC / Shenandoah | Concurrent compaction, pauses in the low milliseconds or below, even on very large heaps | Somewhat lower throughput and more memory/CPU overhead |
Rule of thumb: batch and offline jobs favor Parallel for throughput, typical services favor G1, and latency-sensitive systems with large heaps favor ZGC or Shenandoah.
The tension is always among throughput, latency and footprint: improving one usually costs another.
5. What this means for your code
Garbage collection frees unreachable memory, not unneeded memory. Common leaks:
- Static collections or caches that grow without eviction.
- Listeners/callbacks registered and never removed.
ThreadLocalvalues in pooled threads that are never cleared.- Inner classes or lambdas that accidentally capture a large outer object.
- Classloader leaks in app servers after redeploys, which show up as metaspace growth.
GC also does not manage non-memory resources such as files, sockets and database connections. Close them deterministically with try-with-resources.
Allocation habits matter too: very high allocation rates raise GC frequency, so avoid needless boxing and short-lived large temporary structures in hot paths.
6. Diagnosing problems
OutOfMemoryError has different meanings:
Java heap space: live data exceeds the heap, either a leak or an undersized heap.GC overhead limit exceeded: the JVM spends nearly all its time collecting while reclaiming little.Metaspace: too many classes or a classloader leak.unable to create native threador direct buffer errors: native limits, not heap.
My workflow:
- Enable GC logging (
-Xlog:gc*) and watch heap-after-GC over time. A rising floor after full collections signals a leak. - Capture a heap dump on failure (
-XX:+HeapDumpOnOutOfMemoryError) and inspect it in a tool such as Eclipse MAT or VisualVM, looking at the dominator tree and paths to GC roots. - Use JFR for allocation profiling to see who allocates the most.
- Only then tune: set heap size to leave headroom (live set often targeted at roughly 30 to 50 percent of the heap), choose the collector for the latency goal, and adjust the pause target.
Common mistakes in answers
- Saying Java uses reference counting.
- Claiming memory leaks are impossible in Java.
- Calling
System.gc()as a fix; it is only a hint and often triggers an expensive full collection. - Forgetting that stacks, metaspace and native memory fall outside the heap.
- Tuning flags before measuring.