Lesson 29 • Advanced
Memory Management & Garbage Collection
Understand the heap, stack, GC algorithms, and how to hunt down memory leaks.
Before You Start
You should understand OOP (Lesson 9), Collections (Lesson 13), and Multithreading (Lesson 26). Memory management affects everything — from data structure choices to thread pool sizing.
What You'll Learn
- ✅ Stack vs Heap memory allocation
- ✅ How garbage collection works in Java
- ✅ GC algorithms: Serial, Parallel, G1, ZGC
- ✅ Memory leaks and how to prevent them
- ✅ Strong, Weak, Soft, and Phantom references
- ✅ Tuning JVM memory with -Xms, -Xmx flags
1️⃣ Stack vs Heap Memory
💡 Analogy: Desk vs Warehouse
The stack is your desk — small, organized, auto-cleared when you finish a task. The heap is a warehouse — massive storage, but a janitor (GC) must periodically clean up unused items. Every thread gets its own stack, but all threads share one heap.
| Feature | Stack | Heap |
|---|---|---|
| Stores | Primitives, references | Objects, arrays |
| Speed | Very fast (LIFO) | Slower (GC managed) |
| Size | Small (~512KB-1MB per thread) | Large (up to GBs) |
| Error | StackOverflowError | OutOfMemoryError |
Try It: Object Lifecycle & GC Simulation
// Memory Management — Object Lifecycle
console.log("=== Object Lifecycle ===\n");
// 1. Stack vs Heap
console.log("1. STACK vs HEAP:");
console.log(" int x = 42; → stack (primitive)");
console.log(" new User('Alice'); → heap (object)");
console.log(" Reference to User → stack (pointer)\n");
// 2. Object lifecycle
console.log("2. OBJECT LIFECYCLE:");
class User {
constructor(name) { this.name = name; console.log(" ✅ Created: " + name + " (on heap)"); }
}
let user1 = n
...2️⃣ GC Algorithms & Reference Types
| GC Algorithm | Flag | Best For |
|---|---|---|
| Serial GC | -XX:+UseSerialGC | Small apps, embedded |
| Parallel GC | -XX:+UseParallelGC | Batch processing, throughput |
| G1 GC | -XX:+UseG1GC | Default since Java 9 — balanced |
| ZGC | -XX:+UseZGC | Ultra-low latency (<10ms) |
Reference Types
| Reference | GC Behavior | Use Case |
|---|---|---|
| Strong | Never collected while reachable | Normal variables |
| Soft | Collected when memory is low | Memory-sensitive caches |
| Weak | Collected at next GC | WeakHashMap keys |
| Phantom | Already finalized | Post-mortem cleanup |
Try It: Reference Types & WeakMap
// Reference Types & WeakMap Cache
console.log("=== Reference Types ===\n");
// 1. Strong reference
console.log("1. STRONG REFERENCE:");
let strongRef = { data: "important", size: "50MB" };
console.log(" strongRef:", strongRef.data, "→ never collected while reachable");
strongRef = null;
console.log(" strongRef = null → now eligible for GC\n");
// 2. WeakReference (simulated with WeakRef)
console.log("2. WEAK REFERENCE:");
let obj = { name: "CachedImage", size: "10MB" };
let weakRef = new We
...Try It: JVM Tuning & Profiling
// JVM Memory Tuning
console.log("=== JVM Memory Tuning ===\n");
// 1. JVM flags
console.log("1. ESSENTIAL JVM FLAGS:");
console.log(" java -Xms512m -Xmx2g -XX:+UseG1GC MyApp\n");
let flags = [
{ flag: "-Xms512m", purpose: "Initial heap size (set = -Xmx in prod)" },
{ flag: "-Xmx2g", purpose: "Max heap size (≤80% of RAM)" },
{ flag: "-XX:+UseG1GC", purpose: "G1 garbage collector (default)" },
{ flag: "-XX:MaxGCPauseMillis=200", purpose: "Target GC pause time" },
{ flag: "-X
...Common Mistakes
static List that only adds items is the #1 memory leak pattern in Java.Pro Tips
💡 Set -Xms = -Xmx in production to avoid heap resize pauses.
💡 ZGC (Java 15+) achieves <10ms pauses even with multi-TB heaps — ideal for latency-sensitive apps.
💡 -XX:+HeapDumpOnOutOfMemoryError — always enable this. When OOM hits at 3 AM, you'll have the evidence.
📋 Quick Reference
| Concept | API / Flag | Use Case |
|---|---|---|
| Heap sizing | -Xms / -Xmx | Set initial/max heap |
| GC selection | -XX:+UseG1GC | Choose GC algorithm |
| Weak refs | WeakReference<T> | Cache-friendly references |
| Profiling | jcmd / VisualVM / JFR | Analyze memory usage |
🎉 Lesson Complete!
You now understand Java's memory model, GC strategies, and how to prevent memory leaks!
Next: JVM Internals — classloading, JIT compilation, and bytecode execution.
Sign up for free to track which lessons you've completed and get learning reminders.