Software engineering · java · jvm · garbage-collection · memory · performance
Where Did My Memory Go? A Practical Look at the JVM Heap and Garbage Collection
A latency incident traced to garbage collection, and everything you need to understand it: how the JVM decides what is garbage, why the heap is split into young and old generations, how to read a GC log, how to find a memory leak with a heap dump, how G1, ZGC and the other collectors differ, and which flags are actually worth touching.
Fine for six hours
The pricing service had been boring for months, which is exactly what you want from a pricing service. Then one Tuesday the on-call channel lit up. The p99 latency, normally around 40 milliseconds, was jumping to two seconds. Not all the time. Every forty seconds or so, like a heartbeat.
The odd part was the timing. Every pod had been deployed that morning, and every pod was perfect for the first six hours. Then, one by one, they all started to stutter.
We did the usual things first. The database was fine. The downstream services were fine. CPU was a little higher than usual, but nothing dramatic. Restarting a pod fixed it, and that was the clue we should have taken seriously right away: when a restart fixes something and the problem comes back after a fixed amount of time, something inside the process is slowly filling up.
So we turned on GC logging on one pod and waited. Here is a line from early in the morning:
[612.004s][info][gc] GC(87) Pause Young (Normal) (G1 Evacuation Pause) 1254M->231M(4096M) 9.871ms
And here is the same pod six hours later:
[21598.117s][info][gc] GC(5121) Pause Young (Normal) (G1 Evacuation Pause) 3874M->3790M(4096M) 61.402ms
[21606.903s][info][gc] GC(5126) Pause Full (G1 Compaction Pause) 4095M->3712M(4096M) 1912.337ms
[21647.215s][info][gc] GC(5139) Pause Full (G1 Compaction Pause) 4095M->3718M(4096M) 1887.040ms
If those lines look like noise, don’t worry. By the end of this post you’ll be able to read them at a glance, and you’ll see that they tell the whole story: a two-second pause every forty seconds, and a heap that is almost entirely full of things the JVM is not allowed to throw away.
This is the next post in the series after Java Concurrency Without the Headaches. We’ve spent six posts creating objects. Now let’s talk about where they go.
What “garbage” actually means
When you write new Quote(...), the JVM finds some free space on the heap, the big shared area where objects live, and puts your object there. You never free it. At some point the JVM decides it isn’t needed any more and takes the space back.
How does it decide? It doesn’t look at your object and ask whether you’re done with it. It can’t know that. Instead it asks a simpler question: can the program still reach this object?
Picture a set of starting points that are definitely alive. The local variables on every thread’s stack. The static fields of every loaded class. A few things the JVM itself holds on to. From those starting points, the collector follows every reference, and every reference from those objects, and so on, marking everything it touches. Whatever it never touched is garbage, because there is no path your code could take to get to it.
Those starting points are called GC roots, and following the references is the mark phase. It’s the heart of every collector in the JVM.
Two things fall out of this that surprise people.
First, cycles are fine. If object A points to B and B points to A, but nothing else points to either, both are garbage. There’s no reference counting here, so a cycle doesn’t keep itself alive.
Second, and this is the one that bit us: the JVM will never collect something you can still reach, even if you’ll never use it again. A static map that grows forever is not a bug as far as the collector is concerned. It’s a perfectly healthy, reachable data structure that you happen to never read from. Java can’t leak memory the way C does, by forgetting to free it. It leaks memory by remembering too much.
Once marking is done, the collector has to deal with the space. It can simply note the dead regions as free (that’s sweeping), but that leaves the heap full of little holes. Most JVM collectors instead copy or compact the live objects so they sit next to each other, which leaves one big clean block of free space. That’s also why allocation in Java is so cheap: when free space is one contiguous block, handing out memory is just bumping a pointer forward.
Most objects die young
Here’s an observation that shaped every modern Java collector. Look at what a typical request handler allocates:
QuoteResponse handle(PriceRequest req) {
var lines = req.items().stream() // stream objects: dead in microseconds
.map(this::lineFor) // one PriceLine per item
.toList(); // dead once the response is built
var total = Money.sum(lines); // dead when we return
return new QuoteResponse(req.id(), lines, total); // dead once it's serialized
}
Almost everything here is garbage within a millisecond. A few objects, like the caches, connection pools and Spring beans, live for the whole life of the process. Very little is in between.
This pattern has a name, the weak generational hypothesis, and it holds for nearly every program anyone has measured. The clever bit is what you can do with it. If most objects die young, then a collector that only looks at recently allocated objects will find mostly garbage, and finding garbage is cheap when you only need to trace the few survivors.
So the JVM splits the heap in two.
New objects go into the young generation, specifically into a region called eden. Each thread actually gets its own little slice of eden, a TLAB (thread-local allocation buffer), so allocating doesn’t even need a lock. When eden fills up, the JVM pauses the application briefly and runs a minor collection, also called a young collection: it traces only the young objects, copies the few survivors into a survivor space, and declares the whole of eden empty again. Dead objects cost nothing, because nobody ever visits them.
Objects that survive several young collections (up to 15 by default, the JVM adjusts this as it goes) get promoted into the old generation. That’s where long-lived stuff settles down. The old generation is collected much less often, because it’s big and mostly alive, which makes it expensive to trace.
You might wonder: if the collector only traces young objects, what about an old object that points at a young one? The young object is alive, but no root points to it directly. The JVM handles this with a card table, a small bitmap that remembers which parts of the old generation were written to recently. During a young collection, those dirty “cards” are treated as extra roots. It’s bookkeeping you never see, but it’s why every reference write in Java has a tiny bit of extra work attached, called a write barrier.
Now look at that first log line from the incident again:
[612.004s][info][gc] GC(87) Pause Young (Normal) (G1 Evacuation Pause) 1254M->231M(4096M) 9.871ms
At 612 seconds of uptime, the 87th collection was a young pause. The heap had 1254 MB in use, and afterwards 231 MB. The heap’s total size was 4096 MB, and the pause took about 10 milliseconds. A gigabyte of garbage gone in 10 milliseconds, because almost none of it was alive. That’s the generational design working exactly as intended.
Reading a GC log without fear
You get logs like these with one flag (Java 9 and later):
java -Xlog:gc*:file=gc.log:time,uptime,level,tags:filecount=5,filesize=20m -jar pricing.jar
gc* turns on every GC-related tag, which is chatty but useful when you’re investigating. For everyday production use, plain -Xlog:gc gives you one line per collection, and honestly, I’d leave that on everywhere. It costs almost nothing, and the day you need it, you’ll need it from before the problem started.
When you read a log, the single most useful number is the one after the arrow. After a collection, what’s left in the heap is roughly what’s alive (plus whatever the collector didn’t get around to looking at). If you plot heap usage over time, a healthy service draws a sawtooth: usage climbs as you allocate, drops sharply at each collection, and the bottoms of the teeth stay at about the same height.
Now the incident lines make sense:
# young pause: 3874M -> 3790M. We freed 84 MB out of a 4 GB heap. That's nothing.
[21598.117s] ... Pause Young (Normal) (G1 Evacuation Pause) 3874M->3790M(4096M) 61.402ms
# the collector gave up on doing it incrementally and compacted the whole heap.
# Two seconds, with every application thread stopped.
[21606.903s] ... Pause Full (G1 Compaction Pause) 4095M->3712M(4096M) 1912.337ms
# 40 seconds later, the same thing. And the floor is *higher*: 3712M -> 3718M.
[21647.215s] ... Pause Full (G1 Compaction Pause) 4095M->3718M(4096M) 1887.040ms
After a full collection, 3.7 GB of a 4 GB heap is still alive. So the service is trying to run with about 380 MB of breathing room, and it allocates a few hundred megabytes a second. Every young collection reclaims almost nothing, the old generation has no space to promote into, and the collector falls back to its last resort: stop everything and compact the whole heap. Two seconds later there’s a little room again, the service burns through it in about forty seconds, and around we go.
That’s our heartbeat. The forty seconds wasn’t a timer or a cron job. It was just how long it took to fill the space that was left.
This is also why a GC problem shows up in p99 and not in the average. A two-second pause every forty seconds touches maybe one request in twenty, and the median looks completely normal. If that sounds familiar, it’s the exact effect from Understanding p99 latency.
There’s a second tool worth knowing when you don’t have logs handy. jstat samples the generations from outside the process:
$ jstat -gcutil <pid> 1000
S0 S1 E O M CCS YGC YGCT FGC FGCT CGC CGCT GCT
0.00 100.00 12.50 96.81 97.12 93.40 5121 188.402 37 69.880 412 41.220 299.502
O is old generation occupancy as a percentage: 96.81. FGC is the count of full collections: 37 of them, adding up to 70 seconds of total pause. In a healthy G1 service that count is usually zero, and it should stay zero. If you remember one thing from this section, make it that: a full GC in G1 or ZGC means something has already gone wrong.
So why didn’t anything get collected?
We knew that the heap was full of live objects. The question was which objects, and who was holding them.
The fastest first look is a class histogram. It counts live objects by class, and it’s cheap enough to run on a production pod (it does trigger a full collection, so pick your moment):
$ jcmd <pid> GC.class_histogram | head -8
num #instances #bytes class name (module)
-------------------------------------------------------
1: 21934112 1052837376 [B (java.base@21.0.5)
2: 21933870 526412880 java.lang.String (java.base@21.0.5)
3: 7311290 292451600 com.shop.pricing.QuoteKey
4: 7311290 233961280 com.shop.pricing.Quote
5: 7311302 233961664 java.util.concurrent.ConcurrentHashMap$Node
Byte arrays and strings at the top is normal; almost every Java heap looks like that, because strings store their characters in a byte[]. The interesting lines are below them. Seven million QuoteKeys and exactly as many Quotes and map nodes. Twenty-one million strings is, suspiciously, three per key.
Seven million of anything is a lot for a service that prices a few thousand products. So what was making new keys?
record QuoteKey(String customerId, String sku, String requestId) {}
private final Map<QuoteKey, Quote> quotes = new ConcurrentHashMap<>();
Quote price(PriceRequest req) {
// someone added requestId for tracing. Every request is now a brand-new key.
var key = new QuoteKey(req.customerId(), req.sku(), req.requestId());
return quotes.computeIfAbsent(key, k -> engine.quote(k));
}
There it is. Someone had added the request id to the cache key a few weeks earlier, so it would show up in logs. From that moment, the cache had a hit rate of zero and a retention rate of a hundred percent. Every request added an entry and nothing ever removed one. At about 340 requests a second, seven million entries is just under six hours. The arithmetic matched the incident almost to the minute.
The map is reachable from a field of a Spring singleton, which is reachable from the application context, which is reachable from a static field. As far as the collector is concerned, every one of those seven million quotes is precious.
The fix had two parts. Take requestId out of the key, which restored the hit rate. And stop using an unbounded map as a cache, because the next person to change the key would make the same mistake:
private final Cache<QuoteKey, Quote> quotes = Caffeine.newBuilder()
.maximumSize(100_000) // a cache that can't grow forever
.expireAfterWrite(Duration.ofMinutes(5)) // prices change anyway
.recordStats() // so we'd have seen hitRate() == 0
.build();
A ConcurrentHashMap is a great map. It’s a terrible cache, because a cache needs a rule for forgetting, and a map has none.
The histogram happened to be enough this time. When it isn’t, because the top classes are all byte[] and String and HashMap$Node and you can’t tell whose they are, take a full heap dump:
jcmd <pid> GC.heap_dump /tmp/pricing.hprof
Open it in Eclipse MAT or IntelliJ’s profiler and go straight to the dominator tree. It answers the question “if this object disappeared, how much memory would go with it?” which the tools call retained size. The leak is almost always one object near the top with a huge retained size and a boring name: a map, a list, a ThreadLocal, a listener registry. Follow its path back to a GC root and you’ve found who’s holding on.
Two cautions about heap dumps. They pause the JVM while they’re written, for seconds on a big heap. And they contain everything in memory, including customer data, tokens and passwords, so treat the file like a database backup. It’s still worth adding this to every service, so the dump is waiting for you when the worst happens:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps
The usual suspects
After you’ve chased a few of these, you notice they rhyme. Most Java memory leaks are one of these:
- A map or list used as a cache, with no size limit or expiry
- A listener or callback registered and never unregistered, so the registry holds the listener and everything it captured
- A
ThreadLocalon a pooled thread that’s never removed, so it lives as long as the pool - A lambda or inner class that captures more than you think, like
this, and keeps a whole request object alive - A collection of “pending” work (retries, futures, sessions) where the failure path forgets to remove its entry
You might be tempted to fix leaks with weak references, which let the collector clear an object even while you still point at it, through a WeakReference or a WeakHashMap. They have their place, mostly in framework code that tracks objects it doesn’t own. But they’re a poor cache, because the collector clears them on its schedule, not yours, and an explicit size limit is much easier to reason about.
How the collector picks a pause
Back to the incident for a moment, because one detail is worth understanding. Why was a young pause 10 milliseconds in the morning and 60 in the afternoon? And why did the collector switch to a full compaction at all?
That’s down to how the default collector works. Let’s describe what it does first, and name it after.
Imagine you had to clean a huge warehouse without ever closing it for more than a few minutes. You wouldn’t try to clean everything at once. You’d divide the floor into equal-sized squares. While people work, you’d walk around with a clipboard noting which squares are mostly empty boxes. Then, in each short closure, you’d clean the squares that give you the most space back for the least effort, moving the few useful boxes out of them so the whole square is free. You’d pick how many squares to clean based on how long the closure is allowed to be.
That’s G1, the Garbage-First collector, and the JVM’s default since Java 9. It divides the heap into equal regions, typically a few megabytes each. Any region can be eden, survivor or old, and the roles change over time. While your application runs, G1 marks live objects concurrently, on background threads, so it knows how much garbage each old region holds. Then, during short pauses, it evacuates the regions with the most garbage first (hence the name), copying their survivors elsewhere. It tries to keep each pause under a target, 200 milliseconds by default.
A young pause collects all the eden and survivor regions. A mixed pause collects those plus a handful of the most garbage-filled old regions. Most of the time, that’s all G1 ever does, and the old generation gets cleaned a few regions at a time without a big stop.
But evacuation needs somewhere to copy the survivors to. In our incident, the old regions weren’t full of garbage; they were full of live quotes. G1’s clipboard showed nothing worth cleaning, mixed pauses reclaimed almost nothing, and eventually a young pause tried to copy survivors and found no free region to put them in. At that point G1 does the only thing left: a full GC, stopping every thread and compacting the entire heap. That’s the 1.9 second pause. G1’s full GC is multi-threaded these days, but it’s still a full stop, and its cost grows with the amount of live data, which in our case was nearly everything.
The young pauses grew for a related reason. The more live data each collection has to copy, and the more old-to-young references there are to scan, the longer the pause. G1 also shrinks eden to try to hit its pause target, so collections become more frequent too. Everything degrades together as the heap fills, which is why the latency graph looked fine, then slightly worse, then suddenly terrible.
Picking a collector (or, mostly, not)
The JVM ships several collectors, and they’re really answers to one question: how much pause can you tolerate, and what will you pay to reduce it?
Serial uses one thread and stops the application for every collection. That sounds primitive, and it is, but on a container with one CPU and a few hundred megabytes of heap it’s often the right choice. The JVM picks it automatically on small machines.
Parallel stops the application too, but uses every core to get the job done as fast as possible. If you run batch jobs, where only the total running time matters and nobody’s waiting on an individual request, Parallel usually gives you the most work done per CPU second.
G1 is the balanced default we just met. It aims for pauses of tens to a couple of hundred milliseconds on heaps up to tens of gigabytes, while keeping throughput close to Parallel.
ZGC goes much further. It does almost all its work, including moving objects, while your application keeps running. Moving an object that another thread might be reading sounds impossible, and the trick is that every time your code loads a reference from the heap, a tiny check called a load barrier notices if the object has moved and fixes the reference on the spot. The result is pauses under a millisecond, whether the heap is 1 GB or a few terabytes. It became generational in Java 21 (the default from Java 23, and the only mode from Java 24), so it gets the “most objects die young” benefit as well.
Shenandoah, from Red Hat, takes a similar concurrent-compaction approach to ZGC with a different implementation, and is included in most OpenJDK builds.
Nothing is free, though. Concurrent collectors need spare CPU to do their work in the background, the barriers add a small cost to your own code, and they want more headroom in the heap, because your application keeps allocating while they collect. If the service can’t spare the cores or the memory, a low-pause collector can make things worse.
And here’s the honest part: most services should stay on G1 and never touch a GC flag. G1 is very good, and most “GC problems” are really “my live data is too big” problems, like ours. No collector fixes a leak. ZGC would have turned our two-second pauses into a heap that filled up and then made threads wait for memory, which is a different symptom of the same bug.
If you want to switch, it’s one flag, and it’s an easy experiment:
-XX:+UseZGC # very low pauses, wants spare CPU and heap headroom
-XX:+UseParallelGC # batch jobs where throughput is everything
-XX:+UseSerialGC # tiny containers, one CPU
When I’d reach for ZGC: latency-sensitive services where p99.9 matters, large heaps where G1’s pauses grow, and anywhere you’ve already fixed the allocation and leak problems and still see GC pauses in your tail latency.
The memory that isn’t on the heap
Here’s a different incident you’ll meet eventually. The heap is set to 4 GB, the GC log looks healthy, and Kubernetes keeps killing the pod for using more than its 5 GB limit. There’s no OutOfMemoryError, just an OOMKilled status and a restart.
What’s using the other gigabyte?
The heap is only part of a Java process’s memory. There’s also metaspace, where class metadata lives (a lot of it, with big frameworks). Every thread has its own stack, a megabyte by default, so two hundred platform threads is a fair chunk. The JIT compiler keeps compiled code in the code cache. The garbage collector needs its own data structures. And direct ByteBuffers, which we met in the I/O post, are allocated outside the heap entirely, as are the buffers inside libraries like Netty.
You can ask the JVM for the breakdown if you start it with native memory tracking on:
java -XX:NativeMemoryTracking=summary ...
jcmd <pid> VM.native_memory summary
It’s not perfect (memory allocated by native libraries outside the JVM’s knowledge won’t show up), but it’ll usually tell you which bucket grew.
A few practical rules for containers. The JVM has read container limits since Java 10, and by default it gives the heap only a quarter of the container’s memory, which is often too little. Set it explicitly, either as an absolute size or a percentage:
-Xmx3g # or:
-XX:MaxRAMPercentage=75.0 # 75% of the container limit for the heap
And leave room. A heap at 75 percent of the container limit is a reasonable starting point for most services; with lots of threads, direct buffers or a heavy framework, 60 to 70 percent is safer. If the pod gets killed without an OutOfMemoryError, look off-heap first.
A short list of things worth knowing
I promised fewer lists, but some things really are a checklist. These are the flags and habits that earn their place:
- Always log GC.
-Xlog:gc*:file=gc.log:time,uptime,level,tags:filecount=5,filesize=20m. Cheap, and priceless after the fact. - Dump on OOM.
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=...pointed at a volume with room for a file the size of your heap. - Set the heap size on purpose.
-Xmxor-XX:MaxRAMPercentage. Many teams also set-Xmsto the same value so the heap never has to grow under load. - Stay under 32 GB if you’re near it. Below about 32 GB the JVM stores references in 4 bytes instead of 8 (compressed oops). A 31 GB heap can hold more objects than a 34 GB one.
- Don’t call
System.gc(). With G1 it triggers a full collection by default. If a library does it,-XX:+DisableExplicitGCstops it. - Leave
-XX:MaxGCPauseMillisalone at first. Lowering it makes G1 collect more often with smaller young generations, which can cost more than it saves. Change it only with a measured reason.
Notice what’s missing: dozens of tuning flags for region sizes, tenuring thresholds and thread counts. They exist, and for some specific workload one of them will matter. But I’ve seen far more services made worse by a block of GC flags copied from a 2014 blog post than made better. If a flag is in your startup script and nobody on the team can say why, it’s probably safe to remove it and measure.
The cheapest GC tuning, by far, is allocating less. A few habits help a lot. Don’t keep data in memory longer than you need it. Bound every cache and every queue. Watch for big temporary structures, like reading a whole file or a whole result set into a list when you could stream it. And when you need to know where allocation comes from, Java Flight Recorder will tell you, with almost no overhead:
jcmd <pid> JFR.start duration=60s filename=pricing.jfr settings=profile
Open the recording in JDK Mission Control and look at the allocation view. It shows you which methods allocate the most, which is often a surprise. In our case, a third of all allocation came from a logging call that built a big string at debug level even though debug logging was off.
What I’d do on Monday
If you own a Java service, here’s what I’d do this week. Turn on -Xlog:gc and -XX:+HeapDumpOnOutOfMemoryError everywhere, if they aren’t already. Then pull up a day of GC logs for your busiest service and look at just two things: the heap usage after each collection, and the number of full GCs. If the floor is flat and full GCs are zero, you’re fine, and you can stop worrying about garbage collection for a good while. If the floor creeps upward, run jcmd GC.class_histogram twice, an hour apart, and see which class grew. It’s very likely a map someone thought of as a cache. Give it a size limit, and you’ll probably never need to touch a GC flag at all.
Further reading
- Oracle, HotSpot Virtual Machine Garbage Collection Tuning Guide, the official description of every collector and its flags
- Richard Jones, Antony Hosking and Eliot Moss, The Garbage Collection Handbook (2nd edition), the reference on how collectors work in general
- JEP 248, “Make G1 the Default Garbage Collector”; JEP 307, “Parallel Full GC for G1”; JEP 333, “ZGC: A Scalable Low-Latency Garbage Collector”; JEP 439, “Generational ZGC”; JEP 474, “ZGC: Generational Mode by Default”
- JEP 158, “Unified JVM Logging”, for the full
-Xlogsyntax - The Eclipse Memory Analyzer documentation on dominator trees and retained size
- Aleksey Shipilëv’s “JVM Anatomy Quarks” series, short and precise articles on TLABs, compressed oops, barriers and other internals