Java Tutorial 0/145 lessons ~6 min read Lesson 40

    Memory Management (Heap, Stack, GC)

    memory management (heap, stack, gc) you don't malloc in java — the jvm does it for you. but understanding where objects live

    Course progress0%
    Focus
    13 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    You don't malloc in Java — the JVM does it for you. But understanding where objects live and when they're cleaned up is the difference between a service that runs for months and one that OOMs every weekend.

    Understanding the topic

    JVM memory layout:

    • Stack — one per thread; holds method frames, primitives & references. Tiny, fast, freed on return.
    • Heap — shared; holds every new-allocated object. Garbage-collected.
    • Metaspace — class metadata (replaced PermGen in Java 8).
    • Code cache — JIT-compiled native code.

    Syntax reference

    Heap regions for the G1 GC (default):

    bash
    ┌─────────── HEAP ───────────┐
    │ Young Gen │
    │ ├─ Eden (new objs)
    │ ├─ Survivor S0 │
    │ └─ Survivor S1 │
    ├────────────────────────────┤
    │ Old Gen (long-lived)
    └────────────────────────────┘
    ← Minor GC sweeps Young
    ← Major / Full GC sweeps Old

    Real-world use

    Common production failures:
    Memory leak: a static Map caches user objects forever — heap grows until OOM. Fix: use a WeakHashMap or Caffeine cache with size/TTL bounds.
    GC pause storm: a 32 GB heap with the default G1 occasionally pauses 4 seconds. Fix: switch to ZGC (-XX:+UseZGC) for sub-millisecond pauses.

    Best practices

    • Size the heap explicitly: -Xms2g -Xmx2g. Same min/max avoids resize jitter.
    • Pick a GC: G1 (default), ZGC (low pause), Parallel (throughput).
    • Profile with jcmd, JFR or async-profiler before tuning blindly.

    Purpose of this lesson

    Master Memory Management (Heap, Stack, GC) so you can apply it confidently in production Java code, technical interviews, and code reviews.

    Step-by-step explanation

    1. Understand the core idea behind Memory Management (Heap, Stack, GC).
    2. Walk through the runnable example and tweak it in the playground.
    3. Apply the pattern in a small Spring Boot or CLI exercise of your own.
    4. Re-read the common mistakes and interview Q&A to lock the concept in.

    Interactive workflow diagram

    1JVM memory regions
    1 / 4

    Stack

    Per-thread; holds frames, locals, return addresses.

    Debugging tips

    • Read the full stack trace — Java's exception messages name the offending class and line.
    • Reproduce in the smallest possible main() method before fixing in the real app.
    • Use IntelliJ's debugger breakpoints and 'Evaluate Expression' rather than scattering System.out.

    Optimization strategies

    • Tune heap with -Xms/-Xmx — match Xms to Xmx in production to avoid resize pauses.
    • G1 is the default since Java 9; switch to ZGC/Shenandoah for sub-ms pauses on huge heaps.
    • Use JFR continuously in prod — overhead is <1%.

    Enterprise example

    Teams at Netflix, Uber and Goldman Sachs apply Memory Management (Heap, Stack, GC) daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).

    Interview questions & answers

    Q1Explain Memory Management (Heap, Stack, GC) in one minute.
    Describe what problem it solves, the JDK APIs involved, and one production trade-off.
    Q2When would you avoid Memory Management (Heap, Stack, GC)?
    Mention performance, complexity, or readability cases where a simpler approach wins.

    Summary

    In this lesson you learned Memory Management (Heap, Stack, GC) — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.

    Ready to mark this lesson complete?Track your journey across the entire course.