Java Memory Model
JVM Memory Structure
Learn the JVM Runtime Data Areas, Metaspace, Stack, Heap, and Program Counters.
Interview: Commonly tested on JVM memory regions, the change from PermGen to Metaspace, and heap subdivision.
The JVM executes code within defined memory boundaries called Runtime Data Areas. Knowing which regions are thread-shared vs. thread-isolated is critical for system debugging.
Core Idea
JVM memory is segmented into heap/metaspace (shared) and stack/PC registers (thread-isolated).
Why It Matters
Metaspace uses native memory, meaning class metadata allocation limits are decoupled from JVM Heap constraints.
Interview Lens
Expect questions comparing PermGen (pre-Java 8) to Metaspace and detailing JVM stack frames.
JVM Memory Regions
- Heap: Thread-shared. Stores object instances and array allocations. Managed by GC.
- Metaspace (Method Area): Thread-shared. Stores class structures, method data, constant pool information, and static fields. Allocated from native off-heap memory.
- JVM Stacks: Thread-private. Stores method frames containing local variables and partial evaluation steps.
- PC (Program Counter) Registers: Thread-private. Stores the address of the JVM instruction currently executing.
- Native Method Stacks: Thread-private. Holds stack frames for native (JNI) methods (written in C/C++).
PermGen vs. Metaspace
Prior to Java 8, class metadata was stored in a fixed-size heap region called PermGen (Permanent Generation), which frequently threw java.lang.OutOfMemoryError: PermGen space if frameworks loaded too many dynamic classes. Java 8 replaced this with Metaspace, which dynamically grows using native system memory by default.
Interview-Relevant Information
Q: Where are static variables stored in Java 8+?
Answer: In Java 8+, static variables are stored directly on the Java Heap, coupled with their associated java.lang.Class instance metadata. Class structure definitions and runtime constants remain in Metaspace.
Quick Checklist
Which JVM memory regions are thread-shared? What is Metaspace allocated from? If yes, you understand JVM memory structures.
Use Cases
Configuring container container memory limits to accommodate off-heap Metaspace overhead.
Analyzing stack-frame footprints of thread pools.
Common Mistakes
Assuming Metaspace is part of the JVM Heap (it is allocated off-heap from native host memory).
Neglecting to configure MaxMetaspaceSize in shared staging environments, leading to container termination.