Stop 12 · Multithreading & JVM InternalsTopics · 8/9

JVM Memory (Heap & Stack)

Part of the Java Roadmap

In short

StackOverflowError and OutOfMemoryError are two different problems in two different places. Knowing where your variables and objects live helps you read these errors and answer a favourite interview question.

Each thread has its own stack holding method calls and local variables, while objects live on the shared heap. Running out of each gives StackOverflowError or OutOfMemoryError.

The jaadu sits at a tiny desk stacked with sticky notes while pointing through a doorway at a huge godown full of shelves of cardboard boxes.

Think of it like this

Desk and godown

Every clerk has a small personal desk with sticky notes for the task at hand, and the whole company shares one big godown full of boxes. The desk is the thread's stack, holding method calls and local variables. The godown is the heap, where every object lives. A sticky note can say which shelf a box is on, which is a reference.

Watch it happen

Call stack for one thread

push(main(args))
main(args)

Top of the stack is coloured

1/5main gets a frame. Its local variable order is a reference; the Order object itself is on the heap.

The big ideas

What you need to know

Stack per thread

Each thread has its own stack of frames. Locals and primitive values live here and disappear when the method returns.

Heap is shared

Every object created with new lives on the heap, shared by all threads and cleaned up by the garbage collector.

Two errors

Too deep recursion gives StackOverflowError. Too many live objects gives OutOfMemoryError: Java heap space.

Tuning flags

-Xmx sets max heap, -Xms the starting heap, -Xss each thread's stack size. Metaspace holds class metadata.

See it in code

Walk through the code

java
1public class MemoryDemo {2    record Order(String id, double amount) {}3 4    public static void main(String[] args) {5        int qty = 3;                          // stack6        Order order = new Order("A101", 499); // ref on stack, object on heap7        double tax = calcTax(order.amount() * qty);8        System.out.println(tax);9 10        countDown(1_000_000);                 // too deep!11    }12 13    static double calcTax(double amount) {14        return amount * 0.18;                 // GST at 18%15    }16 17    static void countDown(int n) {18        if (n == 0) return;19        countDown(n - 1);                     // StackOverflowError20    }21}

1/4A primitive local lives inside main's stack frame.

Run with java -Xss256k MemoryDemo.java to hit the stack limit even sooner.

Save yourself the pain

Common mistakes

Oops

Saying 'primitives go on the stack and objects on the heap' with no exceptions.

Do this instead

Local primitives live on the stack, but a primitive field inside an object lives on the heap with that object.

Oops

Raising -Xmx every time you see OutOfMemoryError.

Do this instead

First check for a leak with a heap dump (-XX:+HeapDumpOnOutOfMemoryError). More memory only delays a real leak.

Oops

Fixing a StackOverflowError by increasing -Xss.

Do this instead

Usually the recursion has no proper base case or is too deep. Fix the logic or turn it into a loop.

Your mission

Break both on purpose

~20 min

Quick check

Where does the object created by new StringBuilder() inside a method live?

Go deeper

  1. 1Trigger a StackOverflowError with infinite recursion.
  2. 2Set heap size with -Xms and -Xmx when running a program.
  3. 3Draw where variables and objects live for a short method.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge