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.
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.
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.
- 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.
- Each survival increments an object's age; after a threshold (up to 15) it's promoted to the old generation.
- When the old generation fills, a major/mixed/full collection runs over it — more expensive.
- 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 / approach | What it does |
|---|---|
| Mark | Trace from roots, marking reachable objects |
| Sweep | Free unmarked objects (leaves fragmentation) |
| Compact | Slide live objects together to remove fragmentation (must update all references) |
| Copy | Copy 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
| Collector | Flag | Design | Pauses | Best for |
|---|---|---|---|---|
| Serial | -XX:+UseSerialGC | Single-threaded, STW | Long for big heaps | Small heaps, tiny containers, CLIs |
| Parallel | -XX:+UseParallelGC | Multi-threaded, STW | Moderate | Batch jobs: maximum throughput |
| G1 (default since 9) | -XX:+UseG1GC | Heap divided into ~2,048 regions; concurrent marking; collects regions with the most garbage first; pause-time target | ~10–200 ms, tunable | General-purpose servers |
| ZGC | -XX:+UseZGC | Concurrent marking and relocation using coloured pointers + load barriers; generational since 21 | Under 1 ms, independent of heap size | Low-latency services, huge heaps (up to 16 TB) |
| Shenandoah | -XX:+UseShenandoahGC | Concurrent compaction with forwarding pointers | Few ms | Low latency (Red Hat builds) |
| Epsilon | -XX:+UseEpsilonGC | Allocates, never collects | None (until OOM) | Benchmarks, very short jobs |
G1 in more detail
- 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
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.jarLeave 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:
| Leak | Example |
|---|---|
| Unbounded caches | A static HashMap that only grows — use a bounded cache (Caffeine) with eviction |
| Listeners never removed | Observer registrations held by a long-lived subject (Observer) |
ThreadLocal in thread pools | Values survive across tasks because pool threads never die — always remove() |
Inner class / lambda capturing this | Keeps a large outer object alive |
| Class loader leaks | Redeployed apps whose classes stay referenced → metaspace grows |
| Unclosed resources | Connections, streams, native memory |
| Mutable keys in HashMap | Entries 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
| Type | Collected when | Use |
|---|---|---|
| Strong (normal) | Never while reachable | Everything |
SoftReference | Memory is low | Memory-sensitive caches (prefer a real cache library) |
WeakReference | Next GC once only weakly reachable | WeakHashMap, canonicalising maps, listener lists |
PhantomReference / Cleaner | After finalisation, for cleanup actions | Releasing native resources (replaces deprecated finalize()) |
- 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.
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.