🧠 JVM Memory Areas Explained (With Real-World Examples)
When you run a Java program, the Java Virtual Machine (JVM) manages memory behind the scenes. Understanding how JVM memory works is key for writing efficient, error-free applications — especially for avoiding memory leaks and OutOfMemoryErrors.
📦 1. Heap Memory – The Storage Room
- This is where Java objects live.
- Divided into Young and Old Generations:
- Young Gen: Eden, Survivor 0 (S0), Survivor 1 (S1)
- Old Gen: Long-lived objects
- Managed by Garbage Collector (GC)
🧾 Example: Heap is like a warehouse. New items go to Eden, get tested in Survivors, and permanent items go to Old Gen.
🧵 2. Stack Memory – The Work Desk
- Each thread gets its own stack.
- Stores method calls, local variables, and object references.
- Auto-cleaned when the method finishes.
🧾 Example: Think of it like your desk — you grab tools (variables), do your task (method), then clean up.
🧠 3. MetaSpace – The Class Blueprint Shelf
- Stores metadata about classes (structure, methods, etc.).
- Replaced PermGen in Java 8+
- Uses native memory and grows automatically
🧾 Example: It’s your bookshelf of class blueprints. You don’t change this often.
🔁 Garbage Collection – JVM’s Cleaning Staff
The JVM uses Garbage Collection to clean up memory:
- Minor GC: Cleans Young Gen
- Major GC: Cleans Old Gen
- Removes unreachable objects via Reachability Analysis
How Reachability Works:
Objects are reachable if they can be traced from GC Roots like local variables, static fields, or active thread stacks.
⚠️ Why Should You Care?
- Understand memory leaks and OutOfMemoryError causes
- Fine-tune your application using JVM flags
- Improve performance by writing memory-friendly code
🧩 Final Thoughts
Kitchen Analogy:
Heap = Storage Room
Stack = Workbench
MetaSpace = Blueprint Shelf
GC = Cleaning Staff
🔧 Quick Reference Summary
| Memory Area |
Purpose |
Example |
| Heap |
Object storage |
Warehouse |
| Stack |
Method calls, local vars |
Work desk |
| MetaSpace |
Class metadata |
Bookshelf/manuals |
| GC |
Clean unreachable objects |
Cleaning staff |