memory management
intermediateJVM Memory Areas
Understand where Java puts objects (heap), call frames (stack), and class metadata (metaspace) so you can diagnose OOMs.
The JVM divides its runtime memory into distinct regions, each holding a different kind of data with different lifetimes and failure modes. Knowing which region holds what is the difference between guessing at an OutOfMemoryError and reading its message correctly — the region named in the error tells you immediately where to look.
Heap is a warehouse for products (objects). Stack is each worker's clipboard (per-thread locals). Metaspace is the rulebook section (class blueprints).
Key Concepts
1
The heap is the large, shared region where all objects and arrays live; it is what the garbage collector manages and what you size with -Xmx. It is subdivided generationally into a young generation (where new objects are allocated and most die quickly) and an old generation (for objects that survive long enough to be promoted). Each thread gets its own stack, holding a frame per method call with that method's local variables and partial results; frames are pushed and popped as methods enter and return, and deep or infinite recursion overflows it with a StackOverflowError. Metaspace — which replaced the old PermGen in Java 8 — holds class metadata: the loaded class structures, method bytecode, and the runtime constant pool. It lives in native memory and grows as needed, so leaking class loaders can exhaust it. The smaller PC register and native method stacks round out the per-thread areas.
-XmxStackOverflowError
2
The practical payoff is diagnostic. "OutOfMemoryError: Java heap space" means too many live objects or a heap leak — analyse a heap dump. "OutOfMemoryError: Metaspace" points at class-loading gone wrong, often repeated redeployments leaking loaders. A StackOverflowError is almost always runaway recursion, not a memory shortage. And the heap-versus-stack split explains a fundamental Java fact: object data always lives on the heap, while a local variable holds only a reference to it (or a primitive value) on the stack.
OutOfMemoryError: Java heap spaceOutOfMemoryError: MetaspaceStackOverflowError