JVM Memory & Garbage Collection

How the JVM allocates objects, reachability and GC roots, generational collection, mark-sweep-compact, the collectors (Serial, Parallel, G1, ZGC, Shenandoah), tuning, memory leaks, and reading GC logs.

Advanced 6 min readLesson 10 of 14 Interview Q&A

Java programmers never free memory. The garbage collector (GC) finds objects that can no longer be reached and reclaims their space. Understanding how it works helps you choose a collector, size the heap, read GC logs, and find memory leaks. General GC algorithms are covered in Garbage collection algorithms; this lesson is about the JVM.

Allocation is cheap

New objects are allocated in a TLAB (thread-local allocation buffer) — a chunk of the heap owned by one thread. Allocation is just bumping a pointer: a handful of instructions, no locking. That's why Java can afford to create many short-lived objects.

Each object has a header (12–16 bytes on 64-bit HotSpot: a mark word with hash/lock/GC age bits, plus a compressed class pointer), then its fields, padded to 8 bytes. An Integer takes 16 bytes to store 4 bytes of data — one reason primitive arrays beat collections of boxed numbers.

What is garbage? Reachability

An object is live if it can be reached by following references from a GC root:

  • local variables and operands in active stack frames,
  • static fields of loaded classes,
  • active threads, JNI references, monitors held by threads.

Everything else is garbage — even objects that reference each other in a cycle.

rootsABCDE
A, B, C are reachable. D and E reference each other but are unreachable: both are garbage.

The generational hypothesis

Most objects die young (temporary strings, iterators, request objects); the ones that survive tend to live long (caches, sessions). So the heap is split into generations and the young one is collected often and cheaply.

Edennew objects (TLABs)youngSurvivor S0 / S1objects that survived ≥ 1 minor GCyoungOld (tenured)long-lived objects, promoted after N survivalsold
  1. Eden fills up → minor GC: copy live objects from Eden and the active survivor space into the empty survivor space. Everything left behind is garbage, freed at once — the cost is proportional to live objects, not garbage.
  2. Each survival increments an object's age; after a threshold (up to 15) it's promoted to the old generation.
  3. When the old generation fills, a major/mixed/full collection runs over it — more expensive.
  4. Write barriers and card tables/remembered sets track old→young references so minor GCs don't need to scan the whole old generation.

Core algorithms

Phase / approachWhat it does
MarkTrace from roots, marking reachable objects
SweepFree unmarked objects (leaves fragmentation)
CompactSlide live objects together to remove fragmentation (must update all references)
CopyCopy live objects to a fresh space (young-gen collection); compacts as a side effect

Stop-the-world (STW) pauses halt all application threads so the heap doesn't change under the collector. Modern collectors do most work concurrently with the application, using barriers to track changes, and keep STW pauses short.

The collectors

CollectorFlagDesignPausesBest for
Serial-XX:+UseSerialGCSingle-threaded, STWLong for big heapsSmall heaps, tiny containers, CLIs
Parallel-XX:+UseParallelGCMulti-threaded, STWModerateBatch jobs: maximum throughput
G1 (default since 9)-XX:+UseG1GCHeap divided into ~2,048 regions; concurrent marking; collects regions with the most garbage first; pause-time target~10–200 ms, tunableGeneral-purpose servers
ZGC-XX:+UseZGCConcurrent marking and relocation using coloured pointers + load barriers; generational since 21Under 1 ms, independent of heap sizeLow-latency services, huge heaps (up to 16 TB)
Shenandoah-XX:+UseShenandoahGCConcurrent compaction with forwarding pointersFew msLow latency (Red Hat builds)
Epsilon-XX:+UseEpsilonGCAllocates, never collectsNone (until OOM)Benchmarks, very short jobs

G1 in more detail

EEOSOHH—O—EOO—EO
G1 regions: Eden, Survivor, Old, Humongous (huge objects), free (—). Any region can play any role.
  • Young collections evacuate Eden and Survivor regions (STW, parallel).
  • Concurrent marking starts when the heap reaches a threshold (IHOP, ~45%).
  • Mixed collections then evacuate young regions plus the old regions with the most garbage ("garbage first"), staying within the pause target (-XX:MaxGCPauseMillis=200).
  • A full GC (single-threaded fallback before Java 10, parallel after) means G1 fell behind — investigate.

Sizing and tuning

Shell
java -Xms4g -Xmx4g \                     # initial = max heap avoids resizing
     -XX:+UseG1GC -XX:MaxGCPauseMillis=100 \
     -Xlog:gc*:file=gc.log:time,uptime \
     -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps \
     -jar app.jar

# In containers, size relative to the container's memory limit
java -XX:MaxRAMPercentage=75 -jar app.jar

Leave headroom: the JVM uses memory beyond the heap — metaspace, thread stacks (~1 MB each for platform threads), code cache, direct buffers, GC structures. A container with -Xmx equal to its limit will be OOM-killed.

Memory leaks in a GC'd language

A "leak" in Java is an object that is still reachable but no longer needed:

LeakExample
Unbounded cachesA static HashMap that only grows — use a bounded cache (Caffeine) with eviction
Listeners never removedObserver registrations held by a long-lived subject (Observer)
ThreadLocal in thread poolsValues survive across tasks because pool threads never die — always remove()
Inner class / lambda capturing thisKeeps a large outer object alive
Class loader leaksRedeployed apps whose classes stay referenced → metaspace grows
Unclosed resourcesConnections, streams, native memory
Mutable keys in HashMapEntries that can never be found or removed

Finding them: watch old-gen usage after each full GC trending upwards; take heap dumps (jcmd <pid> GC.heap_dump file.hprof) and analyse dominators in Eclipse MAT or VisualVM; compare two dumps over time.

Reference types

TypeCollected whenUse
Strong (normal)Never while reachableEverything
SoftReferenceMemory is lowMemory-sensitive caches (prefer a real cache library)
WeakReferenceNext GC once only weakly reachableWeakHashMap, canonicalising maps, listener lists
PhantomReference / CleanerAfter finalisation, for cleanup actionsReleasing native resources (replaces deprecated finalize())
Key takeaways
  • Allocation is a pointer bump in a thread-local buffer; most objects die young.
  • Liveness = reachability from GC roots; cycles are collected.
  • Young collections copy survivors; old objects are promoted and collected less often.
  • G1 is the default (region-based, pause targets); ZGC gives sub-millisecond pauses; Parallel maximises throughput.
  • Size the heap for live data plus headroom; reduce allocation before tuning flags.
  • Leaks are unwanted references: caches, listeners, ThreadLocals, class loaders. Use heap dumps.
Interview questions
QHow does generational garbage collection work in the JVM?medium

Based on the observation that most objects die young, the heap is split into a young generation (Eden plus two survivor spaces) and an old generation. New objects go to Eden. Minor GCs copy live objects from Eden and one survivor space into the other, aging them; objects surviving enough cycles are promoted to the old generation. Minor GCs are cheap because they only touch live young objects; the old generation is collected less frequently with mark-compact or region-based concurrent algorithms.

QCan Java have memory leaks?easy

Yes. The GC frees only unreachable objects, so anything still referenced but no longer needed leaks — for example entries in an unbounded static cache, listeners never unregistered, ThreadLocal values in pooled threads, or class loaders retained after redeployment. They show up as old-generation usage that keeps growing after full GCs; heap dumps reveal what holds the references.