JVM Memory & Garbage Collection: What Java Developers Need to Know

The on-call phone buzzed at 2 a.m. The order service was down, and the log's last line was the one every Java developer dreads:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

By 2:20 a.m. the team chat had a confident plan: bump -Xmx from 2g to 8g, redeploy, go back to sleep. By 6 a.m. the service was down again. The extra 6 GB hadn't fixed anything — because the problem was never the heap size. It was an unbounded in-memory "recent orders" cache that grew with every request and was never evicted. No flag fixes a leak.

The same month gave us a second wound, a quieter one. A JSON walker that recursed one level per nested array started throwing StackOverflowError on a customer's deeply nested payload. Someone's first instinct was to raise -Xss. The right fix was a loop instead of recursion — five lines changed, incident closed for good.

Both incidents obey the same law, and it's the spine of this post: diagnose before you tune. Memory problems in the JVM are almost never solved by flags; they're solved by knowing where things live, what the collector actually does, and how to read the evidence the JVM hands you. Every example below is a real program, compiled with javac and run on JDK 21.0.3, with real output — no invented numbers.

By the end, you should be able to look at an OutOfMemoryError, name the memory region it came from, read a GC log line field by field, and explain why you almost never need to touch a GC flag.

1. Heap vs stack vs metaspace: three neighborhoods

The JVM splits memory by lifetime and purpose, not by type. There are three neighborhoods, and confusing them is where most memory debugging goes wrong:

  • Stack — one per thread. Holds local variables and call frames. Memory is freed the instant a method returns. Small, fast, and never garbage collected — a StackOverflowError means runaway recursion, not a leak.
  • Heap — one shared region. Every new object lands here. This is the only region the garbage collector manages. OutOfMemoryError: Java heap space means the heap filled with objects that are still reachable.
  • Metaspace — class metadata (loaded classes, method bytecode). Grows as classes load; a leak here (OutOfMemoryError: Metaspace) usually means a classloader leak — common with hot redeploys, not with normal code.

A tiny program makes the split concrete. The reference lives on the stack; the object lives on the heap:

public class MemoryHood {
    static String shared = "heap: one copy, shared by all threads";  // heap (static field)

    public static void main(String[] args) {
        int count = 3;                       // stack: dies when main() returns
        String greeting = new String("hi");  // stack holds the REFERENCE; "hi" lives on the HEAP
        helper(greeting);
    }

    static void helper(String s) {
        int len = s.length();  // stack: new frame, new locals, freed on return
        System.out.println(len + " " + shared);
    }
}
2 heap: one copy, shared by all threads

Principle: the variable is not the object. Primitives and references live on the stack; the objects those references point to live on the heap. When you say "the stack holds the reference, the heap holds the object," interviews get much easier.

JVM memory map (one process) Stack per thread frame: helper() frame: main() freed on return never GC'd StackOverflowError Heap (shared) the GC's territory Young generation Eden | Survivor 0 | Survivor 1 everything is born here Old generation long-lived survivors graduate here OutOfMemoryError: Java heap space Metaspace class metadata bytecode leak = classloader leak Native thread stacks direct buffers, JNI off-heap ref

Let's see the real numbers. The JDK ships a window into all of this — no flags, no agents, just java.lang.management:

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;

public class MemBeans {
    static String mb(long bytes) {
        return bytes < 0 ? "undefined" : (bytes / 1024 / 1024) + " MB";
    }
    public static void main(String[] args) {
        MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
        MemoryUsage heap = mem.getHeapMemoryUsage();
        MemoryUsage nonHeap = mem.getNonHeapMemoryUsage();
        System.out.println("=== Heap (objects live here, GC manages it) ===");
        System.out.println("init      = " + mb(heap.getInit()));
        System.out.println("used      = " + mb(heap.getUsed()));
        System.out.println("committed = " + mb(heap.getCommitted()));
        System.out.println("max       = " + mb(heap.getMax()));
        System.out.println("=== Non-heap (metaspace, code cache, ...) ===");
        System.out.println("init      = " + mb(nonHeap.getInit()));
        System.out.println("used      = " + mb(nonHeap.getUsed()));
        System.out.println("committed = " + mb(nonHeap.getCommitted()));
        System.out.println("max       = " + mb(nonHeap.getMax()));
        System.out.println("=== Threads ===");
        System.out.println("live threads = " + ManagementFactory.getThreadMXBean().getThreadCount());
    }
}
=== Heap (objects live here, GC manages it) ===
init      = 124 MB
used      = 0 MB
committed = 124 MB
max       = 1984 MB
=== Non-heap (metaspace, code cache, ...) ===
init      = 7 MB
used      = 1 MB
committed = 8 MB
max       = undefined
=== Threads ===
live threads = 6

Four things worth noticing in this real output (values are integer MB, so used = 0 MB just means "under 1 MB"):

  • init vs max: the JVM starts with a 124 MB heap and lets it grow toward 1984 MB as needed. init is where it starts; max is the ceiling. Nothing forced these numbers — I passed no flags at all. (Where 1984 MB comes from is the subject of section 7.)
  • committed vs used: committed is memory the JVM has actually reserved from the OS; used is what's inside it right now. An app can have a huge committed heap and a tiny used heap — which is why "the JVM is using 2 GB" in a monitoring dashboard usually means committed, not live objects.
  • Non-heap max = undefined: metaspace has no default ceiling (we'll confirm this in the flags in section 7). It grows until the OS says no — which is exactly why a classloader leak is so dangerous.
  • 6 live threads for a program whose main does almost nothing — the JVM itself runs GC, JIT, and signal-handler threads. Every one of them has its own stack, each counted against native memory.

2. Where objects are born: Eden, TLABs, and the generational bet

Every new follows the same path. Understanding it explains why allocation in Java is shockingly cheap — and why the collector almost never has to look at old objects:

  1. TLAB first. Each thread gets a private chunk of Eden called a thread-local allocation buffer (TLAB). Allocating inside your TLAB is a pointer bump — a couple of CPU instructions, no lock, no contention. This is why "allocation is cheap in Java" is actually true: the common case never touches a shared structure.
  2. Eden. When your TLAB fills, the thread grabs a fresh one from Eden — the large region where all new objects start life.
  3. Minor GC. When Eden fills, the collector sweeps the young generation only: live objects are copied into a survivor space (and their "age" counter increments); everything else is abandoned in place. No sweeping, no compaction of dead objects — the dead ones are simply never copied.
  4. Graduation. An object that survives enough minor collections (the tenuring threshold is 15 by default — confirmed in this JVM's flags) is promoted to the old generation, which is collected far less often.

The entire design rests on one observed fact — the generational hypothesis: most objects die young. A request-scoped DTO lives for milliseconds; a cached config lives for hours. Collecting them with the same strategy would be wasteful, so young objects get cheap, frequent collections and old objects get rare, expensive ones.

An object's journey through the heap Eden every new object is born here most die here Survivors S0 and S1 copied on each minor GC, age++ Old gen tenured after ~15 survivals rare, costly GCs minor GC tenured Dead objects are never "freed" — the collector copies the live ones and abandons the rest. Copying a mostly-empty Eden is fast. That's the whole trick.

Principle: the collector doesn't find garbage — it finds live objects (everything reachable from GC roots: thread stacks, static fields, JNI handles) and reclaims everything else. A "leak" in Java is never memory the GC forgot; it's objects you kept reachable by accident.

3. What a GC pause actually is

A garbage collection is, at its core, a stop-the-world event: the application threads freeze at safe points while the collector does its copying. During a pause, your code is not running. The pause you see in a log is measured in the same units as your latency budget — which is why GC tuning is really latency tuning.

Modern collectors don't eliminate pauses; they shrink and parallelize them. G1 (the default since Java 9) still stops the world for young-generation evacuation — copying survivors is inherently a "everybody hold still" operation — but it does most old-generation work concurrently with the application. ZGC and Shenandoah push pause times into the sub-millisecond range by making even more of the work concurrent, at the cost of extra CPU and memory overhead. The eternal tradeoff never disappears: throughput vs pause time. A collector that maximizes total work done (throughput) accepts longer pauses; a collector that minimizes pauses spends more CPU doing collection work in the background.

So what does a pause look like from the outside? Exactly like the log line we'll decode next.

4. Reading -Xlog:gc like a native

GC logging is the cheapest diagnostic tool the JVM ships. One flag, zero agents, and the log tells you when collections happened, what kind they were, and exactly how long your application was frozen. Here is a program that simulates short-lived "request data" — allocate, touch, drop:

public class GcStory {
    public static void main(String[] args) {
        // Simulate short-lived "request data": allocate, use briefly, drop.
        for (int i = 0; i < 1200; i++) {
            byte[] request = new byte[256 * 1024]; // 256 KB per "request"
            request[0] = 1;                          // touch it so it is real
            if (i % 200 == 0) System.out.println("request " + i + " processed");
        }
        System.out.println("done -- every request buffer is now garbage");
    }
}
// Run: java -Xlog:gc:file=gc.log GcStory

Program output (nothing surprising — all 1,200 requests "processed"):

request 0 processed
request 200 processed
request 400 processed
request 600 processed
request 800 processed
request 1000 processed
done -- every request buffer is now garbage

And here is the real gc.log — this is the entire file, unedited:

[0.021s][info][gc] Using G1
[0.229s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 6M->1M(126M) 3.535ms
[0.250s][info][gc] GC(1) Pause Young (Normal) (G1 Evacuation Pause) 17M->1M(126M) 2.150ms
[0.302s][info][gc] GC(2) Pause Young (Normal) (G1 Evacuation Pause) 73M->1M(126M) 4.315ms
[0.313s][info][gc] GC(3) Pause Young (Normal) (G1 Evacuation Pause) 73M->1M(126M) 1.339ms
[0.322s][info][gc] GC(4) Pause Young (Normal) (G1 Evacuation Pause) 73M->1M(239M) 4.571ms
[0.502s][info][gc] GC(5) Pause Young (Normal) (G1 Evacuation Pause) 142M->1M(239M) 6.052ms

Let's decode the second line field by field — once you can read one, you can read them all:

[0.229s][info][gc] GC(0) Pause Young (Normal) (G1 Evacuation Pause) 6M->1M(126M) 3.535ms
  • [0.229s] — time since JVM start. Collections at 0.2–0.5s tell you this happened during warmup, not under steady load.
  • [info][gc] — log level and tag. -Xlog:gc enables the gc tag at info level. Want more detail? -Xlog:gc* (all gc tags) or -Xlog:gc+phases=debug for per-phase breakdowns.
  • GC(0) — the collection's sequence number. It makes log lines joinable with heap dumps and JFR events.
  • Pause Young — a stop-the-world pause on the young generation. For the duration at the end of this line, application threads were frozen.
  • (Normal) — a routine evacuation, not one piggybacked on the start of a concurrent cycle.
  • (G1 Evacuation Pause) — G1's cause label: copying live young objects out of Eden into a survivor space.
  • 6M->1M(126M) — heap occupancy before → after, with total heap in parentheses. 6 MB before, 1 MB after: 5 MB of dead request buffers reclaimed, and the heap was 126 MB at the time.
  • 3.535ms — the pause duration. Your application did nothing for 3.5 milliseconds.

Now read the story across all six lines:

  • The program allocated 1,200 × 256 KB ≈ 300 MB of short-lived buffers. Six young collections reclaimed essentially all of it (every line ends at 1M).
  • Nothing ever reached the old generation. The "after" occupancy stays at 1 MB every time — the objects died in Eden, exactly as the generational hypothesis predicts. A healthy application's GC log is boring: young pauses, tiny survivors, no full GCs.
  • The heap grew mid-run: (126M) becomes (239M) at GC(4). That's ergonomics expanding the heap toward its 1984 MB ceiling under allocation pressure — the JVM resizing itself, no flag involved.
  • Average young pause: 3.66 ms. If this were a web service with a 50 ms latency budget, GC would be nowhere near the suspect list — and that's precisely the kind of conclusion you can only draw from the log, not from guessing.

One bonus observation from an earlier run of this same program: when I used 1 MB chunks instead of 256 KB, the log lines read Pause Young (Concurrent Start) (G1 Humongous Allocation). G1 splits the heap into 1 MB regions (confirmed in the flags: G1HeapRegionSize = 1048576), and any object over half a region is "humongous" — allocated directly in the old generation, bypassing Eden entirely. Oversized short-lived objects are a classic hidden GC cost, and the log names them for you.

Principle: when latency spikes, check the GC log before the code. If pauses are 3 ms and your p99 jumped by 300 ms, the collector is innocent — look elsewhere. The log is the alibi.

5. OutOfMemoryError: read the suffix

OutOfMemoryError is not one error — it's a family, and the suffix names the neighborhood from section 1. Each suffix means a different investigation. Let's reproduce the most common one for real.

Flavor 1: Java heap space — reachable objects piling up

The classic: an unbounded cache, a list that only grows, a listener registry nobody unregisters from. This program is the 2 a.m. incident in miniature — a "cache" nobody evicts:

import java.util.ArrayList;
import java.util.List;

public class HeapLeak {
    public static void main(String[] args) {
        List<byte[]> sessionCache = new ArrayList<>(); // the "cache" nobody evicts
        int mb = 0;
        while (true) {
            sessionCache.add(new byte[1024 * 1024]);
            mb++;
            if (mb % 16 == 0) System.out.println("cached " + mb + " MB ...");
        }
    }
}
// Run: java -Xmx64m HeapLeak

I ran it in a subprocess with a deliberately small 64 MB heap (-Xmx64m). Real output:

$ java -Xmx64m HeapLeak
cached 16 MB ...
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at HeapLeak.main(HeapLeak.java:9)

Exit code 1. Note what the JVM is telling you: the error names the heap, and the stack trace points at the allocation site (line 9, the new byte[...]). But the allocation site is rarely the cause — the cause is whatever keeps those arrays reachable. That's why the next step is never a bigger -Xmx. The next step is a heap dump:

$ java -Xmx64m -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/tmp/p5/heapdump.hprof HeapLeak
cached 16 MB ...
java.lang.OutOfMemoryError: Java heap space
Dumping heap to /tmp/p5/heapdump.hprof ...
Heap dump file created [36105108 bytes in 0.065 secs]

$ ls -la /tmp/p5/heapdump.hprof
-rw------- 1 root root 36105108 Oct  6 04:28 /tmp/p5/heapdump.hprof

One flag, and the dying JVM writes a 36 MB snapshot of every live object — in 0.065 seconds. Open that .hprof in VisualVM, Eclipse MAT, or jhsdb, sort by retained heap, and the dominator tree will point at the ArrayList holding tens of megabytes of byte arrays. Principle: -XX:+HeapDumpOnOutOfMemoryError belongs in every production JVM's flags. It's nearly free until the day it saves you — an OOM without a dump is a crime scene with no photographs.

A word of caution the log above makes concrete: the dump is 36 MB for a 64 MB heap. On a production heap of 16 GB, the dump is ~16 GB and takes seconds-to-minutes to write while the process is down. Point HeapDumpPath at a volume with room, and know that the dump only happens once per JVM start by default.

Flavor 2: Metaspace — a classloader leak

Metaspace holds class metadata, and classes are only unloaded when their classloader becomes unreachable. The classic leak: an application server that hot-redeploys WARs — each redeploy creates a new classloader, the old one is pinned by a stray static reference or a leaked thread context, and its classes accumulate forever.

Full honesty here: I tried to reproduce this one live. I generated proxy classes with a fresh classloader per iteration and capped metaspace at 8 MB (-XX:MaxMetaspaceSize=8m). After 100,000 classes in 100 seconds the JVM still hadn't thrown — proxy classes are tiny, and I wasn't going to burn the afternoon waiting. So there's no live demo for this flavor; what matters is recognizing it: OutOfMemoryError: Metaspace after redeploys means "find what pins the old classloader" (a heap dump's classloader histogram shows it), not "raise MaxMetaspaceSize". And note from section 7's flags: the default MaxMetaspaceSize is effectively unlimited, so metaspace only fails when something is genuinely leaking — it's a symptom worth taking seriously.

Flavor 3: Unable to create new native thread — not the heap at all

This one misleads people because it says OutOfMemoryError. It means the OS refused a new thread — you've hit a process/thread limit or exhausted native memory for thread stacks. I didn't reproduce it (spawning threads until the OS says no is a good way to ruin your own afternoon), but the math is simple: each thread reserves a stack (-Xss, default 1 MB on 64-bit Linux). A thousand threads is a gigabyte of native memory before your code allocates a single object. The diagnosis is thread counts and -Xss, never heap flags — and the fix is usually a bounded thread pool or virtual threads, which this track covers in its own post.

Principle: the suffix is the diagnosis. Java heap space → find the accidental retention (heap dump). Metaspace → find the pinned classloader. Unable to create new native thread → count threads, check stack size. Three different neighborhoods, three different investigations, zero flags changed blind.

6. The stack: why StackOverflowError is not a leak

Every method call pushes a frame — return address, parameters, local variables — and every return pops it. The stack is beautifully simple: strictly last-in-first-out, freed the instant a method returns, and completely outside the garbage collector's world. Nothing to tune, nothing to collect.

It breaks exactly one way: recursion without a reachable base case (or legitimate recursion that's simply deeper than the stack). Watch:

public class StackBang {
    static long depth = 0;
    static void recurse() {
        depth++;
        recurse(); // no base case -- every call pushes a frame
    }
    public static void main(String[] args) {
        try {
            recurse();
        } catch (StackOverflowError e) {
            System.out.println("StackOverflowError after " + depth + " nested calls");
        }
    }
}
// Run: java -Xss256k StackBang
StackOverflowError after 1796 nested calls

With a 256 KB stack, this JVM fit 1,796 frames — roughly 146 bytes per frame. That number isn't a constant (it varies with the method's locals and the platform), but the relationship is: depth × frame size ≤ stack size. When the product exceeds the stack, you get the error.

The fix is almost never -Xss. A bigger stack just postpones the same crash by a few thousand frames — and every thread pays for it, since -Xss multiplies by thread count in native memory. Fix the recursion (a loop, an explicit work stack, or tail-call-friendly restructuring), and the problem disappears permanently. Treat StackOverflowError as a code bug wearing a memory costume.

7. Why the JVM defaults are usually right

Every number in this post came from a JVM I never configured. Let's look at what the JVM chose for itself, via -XX:+PrintFlagsFinal:

$ java -XX:+PrintFlagsFinal -version 2>&1 | grep -E "MaxHeapSize|InitialHeapSize|UseG1GC|MaxMetaspaceSize"
   size_t InitialHeapSize   = 130023424            {product} {ergonomic}
   size_t MaxHeapSize       = 2080374784           {product} {ergonomic}
   size_t MaxMetaspaceSize  = 18446744073709551615 {product} {default}
     bool UseG1GC           = true                 {product} {ergonomic}

Three of these four flags say {ergonomic} — the JVM picked them from the machine, not from a human:

  • UseG1GC = true: the low-pause collector is the default. Nobody asked for it; the JVM knows most applications prefer predictable pauses over maximum throughput.
  • MaxHeapSize = 2080374784 bytes ≈ 1984 MB: exactly one quarter of this machine's physical memory. The ergonomic rule (¼ of RAM, within caps) leaves room for the OS, metaspace, thread stacks, and off-heap buffers. This is the same 1984 MB that MemBeans reported as heap max in section 1 — two independent windows, one consistent JVM.
  • InitialHeapSize ≈ 124 MB: start small (¹⁄₆₄ of RAM), grow on demand — which is exactly the (126M) → (239M) growth we watched in the GC log.
  • MaxMetaspaceSize = 2⁶⁴−1: no default ceiling. Sensible — an artificial cap would just convert slow leaks into fast crashes.

This is why "diagnose before you tune" is the spine of the post: the defaults encode twenty years of other people's production incidents. Tune only when measured evidence points at the collector:

  • Frequent long pauses correlating with latency spikes → read the pause times in the GC log first. If pauses are 3 ms and p99 jumped 300 ms, the collector is innocent.
  • Heap keeps growing after full GCs → that's a leak (or an undersized heap), not a tuning problem — take a heap dump, per section 5.
  • Someone suggests -XX:+UseParallelGC "for speed" → ask what the pause-time requirement is. Throughput collectors trade longer pauses for total throughput; for a latency-sensitive API that's the wrong trade, and it's a one-line change to the service's tail latency.

When you do need to look deeper — thread dumps, heap dumps, allocation flame graphs — that's the next post's territory.

Cheat sheet: the only memory flags most developers ever need

  • -Xlog:gc:file=gc.log — GC logging. The first thing you enable when latency looks GC-shaped; the first thing you read, per section 4.
  • -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/dump.hprof — photograph the crime scene. Belongs in every production JVM's flags.
  • -XX:+PrintFlagsFinal — show every flag and its origin ({ergonomic}, {default}, {command line}). Run it before believing any "the JVM does X" claim, including mine.
  • -Xmx / -Xms — heap ceiling / starting heap. Set -Xmx from measured peak usage plus headroom (containers especially); leave -Xms alone unless startup heap sizing shows up in your profiles.
  • -XX:MaxMetaspaceSize — a ceiling for class metadata. Useful as a tripwire (fail fast on a classloader leak in staging) rather than a fix.
  • -Xss — per-thread stack size. You will almost never change this; it's here so you recognize it in someone else's flags and ask why.

Notice what's missing: no collector-selection flags, no generation-size ratios, no tenuring tweaks. That absence is the point — the list above is diagnosis, and diagnosis is what this post was about.

8. The interview one-liners

  • Stack = per-thread locals and frames, freed on return, never GC'd. Heap = all objects, the GC's territory. Metaspace = class metadata; a leak there means a classloader leak.
  • Allocation is cheap: TLAB pointer bumps in Eden, no lock on the fast path. The collector doesn't free dead objects — it copies the live ones and abandons the rest.
  • Generational GC bets most objects die young: cheap frequent minor collections in the young gen, rare expensive collections in the old gen. Tenuring threshold: 15 by default.
  • A GC pause is stop-the-world time — application threads frozen, measured in your latency units. G1 is the default; ZGC/Shenandoah target sub-millisecond pauses. Throughput vs pause time is the eternal tradeoff.
  • Read a GC log line: timestamp, GC(n), pause type and cause, before->after(total) occupancy, pause duration. A healthy log is boring.
  • Read the OutOfMemoryError suffix — it names the neighborhood. And diagnose before you tune: the defaults are usually right.

What's next

Memory is only half the production-diagnosis story. The other half is behavior: what the threads are doing when the service hangs, where the heap actually went, and which allocation site is burning CPU. That's Production Diagnosis: Thread Dumps, Heap Dumps, JFR & async-profiler — where the heap dump we captured in section 5 finally gets opened and interrogated.

Field check before you move on: run HeapLeak yourself with -Xmx64m, confirm the real OutOfMemoryError: Java heap space, then rerun with -XX:+HeapDumpOnOutOfMemoryError and check the .hprof file size against your -Xmx — is the dump roughly the size of the heap, or much smaller, and why? Then run GcStory with -Xlog:gc, compute your own average young-pause time, and find MaxHeapSize in your machine's -XX:+PrintFlagsFinal output — does it equal roughly one quarter of your RAM? If all three check out, you can read a JVM's memory story from its own evidence, and you're ready for production diagnosis.

Continue: Java Learning Roadmap 2026

Comments

Popular posts from this blog

JSP Servlet Interview Questions For Freshers Series 1

What are the core classes and interfaces of hibernate 4

Java Banking Finance Services and Insurance (BFSI) domain interview questions