Courses/Java/Memory Management

    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.

    FeatureStackHeap
    StoresPrimitives, referencesObjects, arrays
    SpeedVery fast (LIFO)Slower (GC managed)
    SizeSmall (~512KB-1MB per thread)Large (up to GBs)
    ErrorStackOverflowErrorOutOfMemoryError

    Try It: Object Lifecycle & GC Simulation

    Try it Yourself »
    JavaScript
    // 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 AlgorithmFlagBest For
    Serial GC-XX:+UseSerialGCSmall apps, embedded
    Parallel GC-XX:+UseParallelGCBatch processing, throughput
    G1 GC-XX:+UseG1GCDefault since Java 9 — balanced
    ZGC-XX:+UseZGCUltra-low latency (<10ms)

    Reference Types

    ReferenceGC BehaviorUse Case
    StrongNever collected while reachableNormal variables
    SoftCollected when memory is lowMemory-sensitive caches
    WeakCollected at next GCWeakHashMap keys
    PhantomAlready finalizedPost-mortem cleanup

    Try It: Reference Types & WeakMap

    Try it Yourself »
    JavaScript
    // 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

    Try it Yourself »
    JavaScript
    // 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

    Calling System.gc(): It's just a hint — the JVM can ignore it. It often causes a Full GC pause at the worst possible time.
    Static collections growing unbounded: A static List that only adds items is the #1 memory leak pattern in Java.
    Not using try-with-resources: Unclosed streams, connections, and cursors leak native memory outside the heap.

    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

    ConceptAPI / FlagUse Case
    Heap sizing-Xms / -XmxSet initial/max heap
    GC selection-XX:+UseG1GCChoose GC algorithm
    Weak refsWeakReference<T>Cache-friendly references
    Profilingjcmd / VisualVM / JFRAnalyze 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.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service