Where the JVM puts things

JVM · lesson 4 of 34 · 4 min read

Heap, stacks, metaspace and code cache - four separate pots, each with its own way of running out.

Open this lesson in the learning hub

Key points

  • Heap holds every object and is shared by all threads. This is the part the garbage collector looks after.
  • Stack is per thread and holds call frames: locals and partial results. A frame is popped the moment the method returns.
  • Locals live on the stack, objects live on the heap. A local variable only holds a reference; the object itself sits elsewhere.
  • Metaspace holds class metadata in native memory. It replaced PermGen in Java 8, so it grows until the machine says no.
  • Code cache holds the machine code the JIT produced. Fill it up and the JVM quietly drops back to interpreting.
  • Each area fails differently, and the message tells you which one: heap space, Metaspace, or StackOverflowError.

Example

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;

public class Main {
    public static void main(String[] args) {
        Runtime rt = Runtime.getRuntime();
        System.out.printf("heap: max=%d MB  committed=%d MB  used=%d MB%n",
                rt.maxMemory() >> 20,
                rt.totalMemory() >> 20,
                (rt.totalMemory() - rt.freeMemory()) >> 20);
        System.out.println();
        System.out.println("every memory area this VM manages:");
        for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
            if (pool.getUsage() == null) { continue; }
            System.out.printf("  %-32s %-16s used=%7d KB%n",
                    pool.getName(), pool.getType(), pool.getUsage().getUsed() >> 10);
        }
        System.out.println();
        System.out.println("Heap pools hold objects. Metaspace holds class metadata.");
        System.out.println("CodeHeap holds JIT-compiled machine code. Stacks are per thread.");
    }
}

Four pots, four limits, four different error messages.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the JVM course, and every lesson in it is listed on the JVM contents page.