Heap, Stack, and Method Area

5 minute read

When you create an object, call a method, or load a class — the JVM stores data in specific memory regions. Understanding these regions is essential for diagnosing OutOfMemoryError, stack overflows, and memory leaks.


JVM Memory Layout

┌──────────────────────────────────────────────────────┐
│                    JVM Process Memory                  │
│                                                        │
│  ┌──────────────────────────────────────────────────┐ │
│  │                    HEAP                           │ │
│  │  (All objects live here — shared across threads)  │ │
│  │                                                    │ │
│  │  ┌──────────┐  ┌──────────┐  ┌───────────────┐  │ │
│  │  │  Young    │  │  Old     │  │  String Pool  │  │ │
│  │  │  Gen      │  │  Gen     │  │  (interned)   │  │ │
│  │  └──────────┘  └──────────┘  └───────────────┘  │ │
│  └──────────────────────────────────────────────────┘ │
│                                                        │
│  ┌─────────┐ ┌─────────┐ ┌─────────┐                 │
│  │ Stack   │ │ Stack   │ │ Stack   │  ← per thread   │
│  │ Thread-1│ │ Thread-2│ │ Thread-3│                   │
│  └─────────┘ └─────────┘ └─────────┘                 │
│                                                        │
│  ┌──────────────────────────────────────────────────┐ │
│  │              Metaspace (off-heap)                 │ │
│  │  Class metadata, constant pool, method bytecode   │ │
│  └──────────────────────────────────────────────────┘ │
│                                                        │
│  ┌─────────────────┐  ┌────────────────────────────┐ │
│  │  PC Registers   │  │  Native Method Stacks      │ │
│  │  (per thread)   │  │  (JNI calls)               │ │
│  └─────────────────┘  └────────────────────────────┘ │
└──────────────────────────────────────────────────────┘

The Heap

The heap stores all objects and arrays. It’s shared across all threads.

String name = new String("Alice");   // "Alice" object → heap
int[] numbers = new int[100];         // array → heap
MyService svc = new MyService();      // object → heap

Heap Generations

┌────────────────────────────────────────────────┐
│                     HEAP                        │
│                                                  │
│  ┌────────────────────────┐  ┌───────────────┐ │
│  │      Young Generation   │  │  Old Gen      │ │
│  │                          │  │  (Tenured)    │ │
│  │  ┌─────┐ ┌────┐ ┌────┐ │  │               │ │
│  │  │Eden │ │ S0 │ │ S1 │ │  │  Long-lived   │ │
│  │  │     │ │    │ │    │ │  │  objects       │ │
│  │  └─────┘ └────┘ └────┘ │  │               │ │
│  └────────────────────────┘  └───────────────┘ │
│        ~1/3 of heap            ~2/3 of heap     │
└────────────────────────────────────────────────┘
Region Purpose Size
Eden New objects allocated here ~80% of young gen
S0, S1 (Survivor) Objects that survived a minor GC ~10% each
Old Gen Objects that survived many GCs ~2/3 of heap

Sizing the Heap

java -Xms512m -Xmx2g -jar app.jar
#     │         │
#     │         └── Maximum heap size
#     └──────────── Initial heap size

Production tip: Set -Xms = -Xmx to avoid heap resizing pauses.


The Stack

Each thread gets its own stack — it stores method call frames.

Thread-1 Stack:
┌─────────────────────────┐
│ Frame: processOrder()    │  ← current method
│   Local: orderId = 42    │
│   Local: total = 99.50   │
│   Operand stack: [...]   │
├─────────────────────────┤
│ Frame: handleRequest()   │  ← called processOrder()
│   Local: request = @ref  │
│   Local: response = @ref │
├─────────────────────────┤
│ Frame: main()            │  ← entry point
│   Local: args = @ref     │
└─────────────────────────┘

What a Stack Frame Contains

Component Stores
Local Variables Method parameters + local variables (primitives by value, objects by reference)
Operand Stack Intermediate computation values
Frame Data Return address, exception table, constant pool reference

Stack vs Heap

Feature Stack Heap
Scope Per thread Shared
Stores Primitives, references Objects
Speed Very fast (LIFO) Slower (GC managed)
Size Small (512KB–1MB default) Large (GBs)
Error StackOverflowError OutOfMemoryError
# Set stack size per thread
java -Xss512k -jar app.jar    # 512KB per thread stack

StackOverflowError

// Infinite recursion → stack overflow
public int factorial(int n) {
    return n * factorial(n - 1);  // no base case!
}
// After ~10,000 frames → StackOverflowError

Metaspace (Method Area)

Metaspace stores class metadata — it replaced PermGen in Java 8.

Stored Data Examples
Class structures Field names, method signatures
Constant pool String literals, numeric constants
Method bytecode Compiled instructions
Annotations Runtime-retained annotations
# Metaspace is off-heap (native memory), but you can limit it
java -XX:MaxMetaspaceSize=256m -jar app.jar

Metaspace vs PermGen

Feature PermGen (Java 7-) Metaspace (Java 8+)
Location Heap Native memory
Default size 64–256MB (fixed) Unlimited (auto-grows)
GC Collected with Full GC Collected when classes unloaded
OOM error PermGen space Metaspace

String Pool

String literals are interned in a pool on the heap:

String a = "hello";          // goes to string pool
String b = "hello";          // reuses same reference from pool
String c = new String("hello"); // new object on heap (NOT pooled)

System.out.println(a == b);  // true  (same reference)
System.out.println(a == c);  // false (different objects)
System.out.println(a.equals(c)); // true (same value)

String d = c.intern();       // adds to pool, returns pooled reference
System.out.println(a == d);  // true

Object Memory Layout

Every Java object in memory has:

┌───────────────────────────────────────┐
│           Object Header               │
│  ┌─────────────────────────────────┐  │
│  │ Mark Word (8 bytes)             │  │  ← hash code, GC age, lock state
│  ├─────────────────────────────────┤  │
│  │ Class Pointer (4 or 8 bytes)    │  │  ← points to class metadata
│  └─────────────────────────────────┘  │
├───────────────────────────────────────┤
│           Instance Data               │  ← your fields
│  int age = 25           (4 bytes)     │
│  boolean active = true  (1 byte)      │
│  String name = @ref     (4 bytes)     │
├───────────────────────────────────────┤
│           Padding                     │  ← align to 8-byte boundary
│  (3 bytes padding)                    │
└───────────────────────────────────────┘
Total: 8 + 4 + 4 + 1 + 4 + 3 = 24 bytes

An empty new Object() costs 16 bytes (12-byte header + 4 padding).

Compressed Oops

On 64-bit JVMs with heaps < 32GB, compressed oops shrinks object references from 8 bytes to 4 bytes:

java -XX:+UseCompressedOops -jar app.jar   # on by default for heaps < 32GB

This is why keeping your heap under 32GB is a common recommendation — you get compressed oops for free.


Program Counter (PC) Register

Each thread has a PC register pointing to the current bytecode instruction being executed. It’s small and managed internally — you never interact with it directly.


Native Method Stack

Used for JNI (Java Native Interface) calls — when Java calls C/C++ code:

public class NativeExample {
    public native void nativeMethod();  // implemented in C
    static { System.loadLibrary("mylib"); }
}

Common Mistakes

Mistake Problem Fix
Setting -Xmx too low Frequent GC, OutOfMemoryError Profile actual usage, set appropriately
Setting -Xmx too high OS swap, long GC pauses Don’t exceed physical RAM
Not setting -Xms = -Xmx Heap resizing pauses Set them equal in production
Creating millions of small objects GC pressure, high allocation rate Reuse objects, use primitives
Deep recursion without tail optimization StackOverflowError Convert to iteration

Key Takeaways

  1. Heap = objects (shared), Stack = method frames (per thread), Metaspace = class metadata (off-heap).
  2. Heap is generational: Eden → Survivor → Old Gen.
  3. Set -Xms = -Xmx in production to avoid resizing pauses.
  4. An empty Object costs 16 bytes. Every object has a header.
  5. Compressed oops (heaps < 32GB) save significant memory.
  6. String pool deduplicates string literals automatically.

What’s Next?

Next: Garbage Collection — how the JVM reclaims memory and which GC algorithm to choose.

Updated: