JVM Memory Architecture: Heap, Metaspace & Thread Stacks
1Concept
JVM memory is partitioned into: 1. Heap (shared across threads, housing all objects); 2. Metaspace (native OS RAM housing class metadata, method bytecode, and interned strings); 3. Thread Stacks (per-thread memory holding local frames, operand stacks, and method call chains); 4. PC Registers; 5. Native Method Stacks.
2Architecture Diagram
+-------------------------------------------------------------------------+ | JVM RUNTIME MEMORY MODEL | | +------------------------------------+ +---------------------------+ | | | HEAP MEMORY (Shared by all threads)| | METASPACE (Native RAM) | | | | +----------------+ +------------+ | | - Class Metadata | | | | | Young Gen | | Old Gen | | | - Method Bytecode | | | | | (Eden, S0, S1) | | (Tenured) | | | - Constant Pool | | | | +----------------+ +------------+ | +---------------------------+ | | +------------------------------------+ | | +-------------------------------------------------------------------+ | | | PER-THREAD MEMORY: Thread Stack Frames | PC Register | Native Stack| | | +-------------------------------------------------------------------+ | +-------------------------------------------------------------------------+
3Code Example
Core Java
public class JvmMemoryMetricsDemo {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
long mb = 1024 * 1024;
System.out.println("=== JVM Runtime Memory Metrics ===");
System.out.println("Available CPU Processors: " + runtime.availableProcessors());
System.out.println("Total Memory Allocated: " + (runtime.totalMemory() / mb) + " MB");
System.out.println("Free Memory in JVM: " + (runtime.freeMemory() / mb) + " MB");
System.out.println("Max Memory Limit (-Xmx): " + (runtime.maxMemory() / mb) + " MB");
}
}4Expected Output
=== JVM Runtime Memory Metrics === Available CPU Processors: 8 Total Memory Allocated: 256 MB Free Memory in JVM: 248 MB Max Memory Limit (-Xmx): 4096 MB
5Key Takeaways
- ✓Metaspace replaced PermGen in Java 8 and grows dynamically in native OS RAM by default.
- ✓StackOverflowError occurs when thread recursion exceeds stack frame depth (`-Xss`).
- ✓OutOfMemoryError: Java heap space occurs when active objects exceed `-Xmx`.