Java
Module 30: JVM & Memory ManagementBeginner28 min read

JVM Memory Areas, Stack vs Heap & Garbage Collection

Master Heap generations (Young/Old), Thread Stacks, Metaspace, G1/ZGC Garbage Collectors, and diagnosing memory leaks.

Key Takeaways & Core Concepts
  • Young Generation (Eden + Survivor S0/S1): Fast Minor GC sweeps short-lived objects in milliseconds.
  • Old (Tenured) Generation: Objects that survive multiple Minor GCs are promoted here and collected by Major / Mixed GC.
  • Modern Collectors: G1GC (default since Java 9, balances throughput and pause times) and ZGC (Generational ZGC in Java 21 achieves sub-millisecond pauses on multi-GB/TB heaps).

JVM Runtime Data Areas

Memory AreaScopeStores
HeapShared across all threadsAll object instances & arrays (Young Gen: Eden/S0/S1 + Old Gen)
JVM StackPer-threadStack frames, local primitives, object references, return addresses
MetaspaceNative OS memory (Java 8+)Class metadata, method bytecode, static references (replaced PermGen)
PC RegisterPer-threadAddress of currently executing bytecode instruction
Inspecting JVM Heap & Processor Limits
1public class Main {
2 public static void main(String[] args) {
3 Runtime rt = Runtime.getRuntime();
4 long mb = 1024 * 1024;
5 System.out.println("Available Processors: " + rt.availableProcessors());
6 System.out.println("Total Heap (MB): " + (rt.totalMemory() / mb));
7 System.out.println("Max Heap (MB): " + (rt.maxMemory() / mb));
8 }
9}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
9 lines
Note: `-Xms` and `-Xmx` JVM flags control initial and maximum heap sizes.

Generational Garbage Collection Hypothesis

Most objects die young (temporary loop iterators, DTOs, strings). Therefore, the Heap is divided into:

  • Young Generation (Eden + Survivor S0/S1): Fast Minor GC sweeps short-lived objects in milliseconds.
  • Old (Tenured) Generation: Objects that survive multiple Minor GCs are promoted here and collected by Major / Mixed GC.
  • Modern Collectors: G1GC (default since Java 9, balances throughput and pause times) and ZGC (Generational ZGC in Java 21 achieves sub-millisecond pauses on multi-GB/TB heaps).

How Memory Leaks Happen in Java

Garbage Collection only reclaims unreachable objects. A memory leak occurs when unused objects stay reachable from GC Roots:

  • Unbounded static caches or HashMaps that never evict entries.
  • ThreadLocal variables not cleared with .remove() inside thread pools.
  • Unclosed streams/connections or registered event listeners that are never unregistered.
Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)