Expert · Design patterns, JVM internals and interviews · topic 58 of 60 · 25 min
JVM memory and garbage collection
Explanation
Where things live
| Area | Holds | Per | Error when full |
|---|---|---|---|
| Stack | Method call frames, local variables, primitive locals and references | Thread | StackOverflowError |
| Heap | All objects and arrays (new …) | JVM (shared) | OutOfMemoryError: Java heap space |
| Metaspace | Class metadata (since Java 8; replaced PermGen) | JVM | OutOfMemoryError: Metaspace |
void placeOrder() {
int qty = 2; // on this thread's stack
Order order = new Order("Asha", qty); // reference on the stack, Order object on the heap
} // frame popped; the Order is unreachable unless stored elsewhereGarbage collection
The garbage collector (GC) finds objects that cannot be reached from any "root" (local variables of running threads, static fields, and so on) and reclaims their memory. Most objects die young (temporary strings, DTOs for one request), so collectors split the heap into a young generation (collected often and quickly) and an old generation (for long-lived objects, collected less often). This is called generational collection.
- G1 (Garbage-First): the default collector since Java 9; balances throughput and pause times for most server apps.
- ZGC and Shenandoah: low-pause collectors for very large heaps and latency-sensitive services.
- Parallel GC: maximum throughput for batch jobs that can tolerate longer pauses.
Sizing the heap
java -Xms512m -Xmx2g -jar app.jar # start with 512 MB, allow up to 2 GB of heap
java -XX:+UseZGC -Xmx8g -jar app.jar # choose a collector
java -Xlog:gc -jar app.jar # log GC activity
jcmd <pid> GC.heap_info # inspect a running JVMMemory leaks in Java
The GC frees only UNREACHABLE objects. A leak in Java means something still references objects you no longer need, so they can never be collected. Common causes: static collections that only grow (a static Map used as a cache with no limit), listeners or callbacks registered and never removed, ThreadLocal values not cleaned up in thread pools, and unclosed resources.
class SessionCache {
private static final Map<String, Session> SESSIONS = new HashMap<>(); // grows forever
static void add(Session s) { SESSIONS.put(s.id(), s); } // never removed → leak
}
// Fix: remove on logout, add expiry, or use a bounded cache (Caffeine) / a WeakHashMap where suitable.Errors to recognise
- java.lang.OutOfMemoryError: Java heap space → the heap is full of live objects: a leak, or genuinely too little -Xmx.
- java.lang.StackOverflowError → usually unbounded recursion.
- GC overhead limit exceeded → the JVM spends almost all its time collecting and freeing almost nothing.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
JVM memory and garbage collection · 1/6
In this lesson you will see how the JVM manages memory.
Prefer a video by a teacher? Find free videos on “jvm memory model stack vs heap garbage collection g1 explained” on YouTube ↗
In real life: A leak found with a heap dump
An insurance company's quote service ran out of memory every few days. A heap dump taken automatically at the OutOfMemoryError showed 3 million QuoteRequest objects held by a static HashMap that was meant to cache recent quotes but never evicted anything. Replacing it with a size-limited cache with expiry fixed the problem.
java -Xmx1g -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/var/dumps -jar quote-service.jarPractice (0/3 done)
Where does the object created by new Order() live?
A recursive method without a base case crashes with…
Write a small program that keeps adding 1 MB byte arrays to a static List in a loop. Run it with -Xmx64m and observe the OutOfMemoryError. Run again with -XX:+HeapDumpOnOutOfMemoryError, open the dump in VisualVM or Eclipse MAT, and find what holds the memory. Then fix the "leak" by clearing the list every 10 items.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Java interview questionsDesign patterns, JVM internals and interviews · same module
- SOLID principlesDesign patterns, JVM internals and interviews · same module
- Memory and garbage collectionJavaScript Programming (language in depth) · Performance and Node.js
- Memory 101: the stack and the heapRust Programming · Ownership: Rust's big idea
- Stack and heapC Programming (from zero to systems) · Dynamic memory
- What Rust is and why learn itRust Programming · Getting started with Rust
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which is the default garbage collector in modern JDKs?
Answer: G1
G1 has been the default since Java 9.
What replaced PermGen in Java 8?
Answer: Metaspace
Class metadata moved to Metaspace.
Can Java programs have memory leaks?
Answer: Yes, when unneeded objects are still referenced
The GC only frees unreachable objects.
What does -Xmx2g set?
Answer: The maximum heap size
-Xss sets the thread stack size.
When can the garbage collector free an object?Related
Answer: When no reachable reference points to it
Reachability decides what is kept.
How does Rust decide when to free heap memory?Related
Answer: Ownership rules let the compiler insert the free at the right point
Rust frees a value when its owner goes out of scope, decided at compile time.
Who frees heap memory in C?Related
How does Rust free memory?Related
Answer: Through ownership: a value is freed when its owner goes out of scope
Ownership rules make freeing automatic and predictable, and the compiler checks them.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 2 more topics in “Design patterns, JVM internals and interviews” before its exam: Java interview questions, Projects and a Java career.
- Module 12 exam: Design patterns, JVM internals and interviews · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- 60 topics left in the course before the final exam.