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 Area | Scope | Stores |
|---|---|---|
| Heap | Shared across all threads | All object instances & arrays (Young Gen: Eden/S0/S1 + Old Gen) |
| JVM Stack | Per-thread | Stack frames, local primitives, object references, return addresses |
| Metaspace | Native OS memory (Java 8+) | Class metadata, method bytecode, static references (replaced PermGen) |
| PC Register | Per-thread | Address 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
staticcaches orHashMaps that never evict entries. ThreadLocalvariables 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)