JVM memory & garbage collection basics
Explain heap, stack and GC well enough to debug memory issues.
By Invicly Tech, , in Backend Java Development. About 12 minutes to read.
In short
The JVM splits memory into the heap for objects, a stack per thread for method calls, and metaspace for class data. The garbage collector frees heap objects that nothing references any more.
Explained simply
When your Java program runs, the JVM asks the operating system for memory and divides it into areas. The biggest is the heap, where every object lives. Each thread also has its own small stack for the methods it is currently running.
In Java you never free memory yourself. The garbage collector (GC) does it. From time to time it finds objects that nothing can reach any more and reclaims their space. This removes whole classes of bugs, but the GC needs CPU time and sometimes pauses your program briefly.
Java can still leak memory. If your code keeps a reference to objects it no longer needs, for example in a static map that only grows, the GC must keep them. The heap fills up, the GC runs more and more often, and finally the app crashes with OutOfMemoryError.
To debug memory you use a few tools: GC logs show how often the GC runs and how much it frees, and a heap dump is a snapshot of every object. With VisualVM or Eclipse MAT you can open a dump and see which objects hold the most memory and who is keeping them alive.
Press Play on a diagram to walk through it one step at a time.
- 1Heap: young generation
Eden plus survivor spaces; new objects live here
- 2Heap: old generation
Long-lived objects promoted from young gen
- 3Thread stacks
One per thread: frames, local variables, references
- 4Metaspace
Class metadata, stored in native memory
- 5Code cache
Machine code produced by the JIT compiler
- 1Allocate in Eden
New objects are created quickly in Eden
- 2Minor GC
Eden fills; unreachable objects are discarded
- 3Copy survivors
Live objects move to a survivor space
- 4Promote to old gen
Objects surviving several GCs are promoted
- 5Major or mixed GC
Old gen is collected when it fills up
- Back to step 1
- 1Notice the symptom
Memory climbs, GC runs more often, latency rises
- 2Check GC logs
Is heap-after-GC rising over hours?
- 3Take two heap dumps
jcmd GC.heap_dump, some time apart
- 4Compare in MAT or VisualVM
Which classes grew the most?
- 5Follow path to GC root
Find the field that holds them
- 6Fix and verify
Bound or remove it, then watch the logs again
In depth
How big is the heap, really?
If you set nothing, the JVM uses a maximum heap of one quarter of the available memory. The JVM is container-aware, so inside Docker or Kubernetes it reads the container memory limit, not the host's RAM. On a 2 GB container you get a 512 MB heap by default, which is often too small. Set the heap with -Xmx (maximum) and -Xms (initial), or, better for containers, use -XX:MaxRAMPercentage=75 so the heap scales with the limit.
The heap is not the whole process. Thread stacks (about 1 MB each by default on 64-bit Linux, set with -Xss), metaspace for classes, the JIT code cache, direct byte buffers used by Netty and NIO, and the GC's own data all live outside it. That is why the process uses more memory than -Xmx.
- -Xmx2g sets a 2 GB maximum heap
- -XX:MaxRAMPercentage=75 sizes the heap from the container limit
- java -XX:+PrintFlagsFinal -version shows every default
Choosing a garbage collector
All modern collectors are generational or region-based and stop the application only briefly, but they trade different things. Throughput is how much CPU time goes to your code rather than the GC; latency is how long the pauses are. G1 has been the default since Java 9. It splits the heap into equal regions, collects the ones with most garbage first, and tries to meet a pause goal, 200 ms by default (-XX:MaxGCPauseMillis). Parallel GC maximises throughput and suits batch jobs that do not mind longer pauses. ZGC does almost all work concurrently and keeps pauses under a millisecond even on huge heaps, at the cost of some extra CPU and memory. On a machine with fewer than 2 CPUs or under about 1.8 GB of memory, the JVM quietly picks the Serial collector unless you choose one.
- Best raw throughput
- Longer stop-the-world pauses
- Good for batch jobs
- Simple to tune
- Region-based heap
- Pause goal, 200 ms by default
- Balanced for most services
- Works well from 1 GB up
- Pauses usually under 1 ms
- Generational since Java 21
- Scales to very large heaps
- Uses a bit more CPU and RAM
Reading GC logs
Turn on logging with -Xlog:gc (short) or -Xlog:gc* (detailed), and add :file=gc.log to write to a file. A typical G1 line looks like: GC(41) Pause Young (Normal) (G1 Evacuation Pause) 410M->95M(512M) 7.8ms. Read it as: collection number 41, a young collection, heap used before was 410 MB, after was 95 MB, total heap is 512 MB, and the app was paused for 7.8 ms.
What to look for: short young pauses every few seconds are normal. The number after the arrow is the live data that survived. If that number keeps rising over hours, even after full collections, something is holding on to objects. Lines with Pause Full mean the GC had to stop everything and compact, which in G1 usually means the heap is too small or there is a leak. jstat -gcutil PID 1000 shows the same picture live, once per second.
- -Xlog:gc*:file=gc.log:time,uptime,level,tags
- Watch heap-after-GC over time, not heap-before
- Frequent Pause Full lines are a red flag
Heap dumps and finding the leak
A heap dump is a file with every object on the heap and every reference between them. Take one from a running app with jcmd PID GC.heap_dump /tmp/app.hprof, or let the JVM write one automatically with -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dumps. Dumps are roughly as big as the used heap and pause the app while being written, so be careful in production.
Open the file in Eclipse MAT or VisualVM (a separate download since Java 9). Two sizes matter. Shallow size is the memory of the object itself. Retained size is how much memory would be freed if that object disappeared, including everything only it keeps alive. Sort by retained size, pick the biggest, and follow its path to a GC root, such as a static field or a running thread. That path names the code that holds the memory.
- HashMap (retained 1.4 GB)
- HashMap$Node[] table
- 2.1 million entries
- Each entry
- String key: request id
- RequestInfo value
- Each RequestInfo
- byte[] request body
- Headers map
Kinds of OutOfMemoryError
The message after OutOfMemoryError tells you which area ran out, and each needs a different fix. Java heap space means the heap is full: find a leak or raise -Xmx if the live data really is bigger. GC overhead limit exceeded means the JVM spends almost all its time in GC and frees almost nothing, which is a leak in most cases. Metaspace means too many classes were loaded, often from repeated hot redeploys or runaway code generation. Unable to create native thread means the OS refused more threads. Direct buffer memory points to off-heap buffers.
In containers there is one more case: the process is killed with exit code 137 and no Java error at all. The total process memory passed the container limit, so the kernel killed it. Lower the heap percentage to leave room for non-heap memory.
- Java heap space: leak or heap too small
- Metaspace: class loading problem
- unable to create native thread: too many threads
- Exit code 137: container OOM kill, not a Java OOM
Learn it in 4 short steps
About 1h each. Track them with a timer in your plan.
- 1Learn heap, stack and metaspace~1h
- 2Compare common GC algorithms~1h
- 3Read GC logs and heap dumps~1h
- 4Diagnose a memory leak with VisualVM~1h
Key points
- Objects live on the heap; local primitives and references live on the thread stack.
- Most objects die young, so collecting the young generation is cheap and frequent.
- G1 is the default collector; ZGC targets very short pauses on large heaps.
- A memory leak in Java is objects still referenced, often from static maps or caches.
Key terms
Tap a card to flip it. 0/5 known
Examples
# Fixed 512 MB heap, G1 collector, GC log, dump on OOM
java -Xms512m -Xmx512m -XX:+UseG1GC -Xlog:gc:file=gc.log -XX:+HeapDumpOnOutOfMemoryError -jar app.jar
# Inspect a running JVM
jcmd <pid> GC.heap_info
jcmd <pid> GC.heap_dump /tmp/heap.hprof
# Open heap.hprof in VisualVM or Eclipse MAT to find what holds memoryReading a worrying GC log
An API gets slower every few hours. Step 1: you enable -Xlog:gc and look at the lines. Step 2: young pauses are short, which is fine, but the heap-after-GC value climbs from 95 MB to 330 MB over an hour. Step 3: then a Pause Full appears that frees almost nothing and takes over a second. Step 4: conclusion: live data is growing without limit, so this is a leak, not a tuning problem. Raising -Xmx would only delay the crash. Next step: take a heap dump.
[ 120.4s][info][gc] GC(41) Pause Young (Normal) (G1 Evacuation Pause) 410M->95M(512M) 7.8ms
[ 1310.9s][info][gc] GC(390) Pause Young (Normal) (G1 Evacuation Pause) 452M->160M(512M) 9.1ms
[ 2402.2s][info][gc] GC(702) Pause Young (Normal) (G1 Evacuation Pause) 470M->240M(512M) 11.6ms
[ 3605.7s][info][gc] GC(988) Pause Young (Normal) (G1 Evacuation Pause) 488M->330M(512M) 14.0ms
[ 3911.3s][info][gc] GC(1032) Pause Full (G1 Compaction Pause) 505M->498M(512M) 1450.2msFinding and fixing a static map leak
Step 1: take a heap dump with jcmd and open it in VisualVM or MAT. Step 2: sort by retained size; one HashMap holds most of the heap. Step 3: the path to the GC root shows the static field AuditService.SEEN. Step 4: the code adds every request and never removes anything. Step 5: fix it with a bounded cache that caps the size and expires old entries, or stop storing the data at all. Step 6: deploy and confirm in the GC logs that heap-after-GC stays flat.
public class AuditService {
// Leak: grows on every request and is never cleared
private static final Map<String, RequestInfo> SEEN = new HashMap<>();
public void record(String requestId, RequestInfo info) {
SEEN.put(requestId, info);
}
}
// Fix: a bounded cache (Caffeine)
private final Cache<String, RequestInfo> seen = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(Duration.ofMinutes(10))
.build();Quick reference
- Default max heap is 1/4 of available memory, including inside containers
- Use -XX:MaxRAMPercentage=75 in containers instead of a fixed -Xmx
- -Xlog:gc*:file=gc.log turns on detailed GC logging (Java 9+)
- jcmd PID GC.heap_dump /tmp/app.hprof writes a heap dump
- -XX:+HeapDumpOnOutOfMemoryError captures the moment of failure
- Retained size, not shallow size, shows what really holds memory
- jstat -gcutil PID 1000 prints GC usage every second
- Exit code 137 in a container means the kernel killed the process for memory
Common mistakes
- Raising -Xmx to hide a leak instead of finding what holds references.
- Unbounded static caches that grow forever.
- Deep or infinite recursion causing StackOverflowError.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Print the maximum heap the JVM will use. Run it once with no flags and once with -Xmx256m, and compare.
- Exercise 2medium
Write a recursive method that counts how deep it can go before StackOverflowError. Run it with the default stack and with -Xss4m and compare the depth.
- Exercise 3hard
Write a program that leaks memory into a static list, run it with -Xmx128m and -XX:+HeapDumpOnOutOfMemoryError, then open the dump and find the field holding the memory.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does calling System.gc() help?
- Usually not. It is only a hint, it can trigger an expensive full collection, and the GC already knows better when to run. Fix what holds memory instead.
- Can Java have memory leaks if it has a garbage collector?
- Yes. The GC only frees unreachable objects, so anything still referenced, such as entries in a static map, a listener list or a ThreadLocal in a pooled thread, stays forever.
- What is the difference between StackOverflowError and OutOfMemoryError?
- StackOverflowError means one thread's stack is full, almost always from too-deep or endless recursion. OutOfMemoryError means a shared memory area, usually the heap, is exhausted.
- Should I set -Xms equal to -Xmx?
- For servers it is common, because the heap never has to grow or shrink and memory use is predictable. In containers, percentage flags such as MaxRAMPercentage are often easier to manage.