#JVM memory: heap, stacks and metaspace
AddedWhen a JVM runs your program it divides memory into a few areas, and the Java Virtual Machine Specification (chapter 2, "Run-Time Data Areas") names them:
- The heap, shared by all threads: every object and every array, from
new Order()to aStringto abyte[]. The garbage collector manages it. Its maximum size is-Xmx; by default it's a quarter of the machine's (or container's) memory. - A stack per thread: one frame per method call, holding that call's local variables (primitives directly, objects as references to the heap) and partial results. The stack size is
-Xss(2 MB by default on macOS and Linux on ARM, 1 MB on x64, per thejavaman page). Frames disappear when methods return; no GC needed. - Metaspace: class metadata (each loaded class's structure, methods, constant pool), in native memory outside the heap. Before Java 8 this was the "permanent generation" (PermGen), a fixed-size part of the heap you had to size by hand in Java 6 days; since Java 8 it's Metaspace, and its size isn't limited by default.
- Plus memory the JVM itself uses: JIT-compiled code (the code cache), GC bookkeeping, thread structures, and direct (off-heap) buffers. That's why a JVM process uses more memory than
-Xmx.
The mental model for a Node developer: it's the same picture as V8. V8 also has a heap for objects (managed by its GC) and a call stack for frames, and "Maximum call stack size exceeded" is V8's version of StackOverflowError. The differences are in the knobs: V8's old space is capped by --max-old-space-size; the JVM's heap by -Xmx. And the JVM runs many threads, so it has many stacks (one per thread) and one shared heap.
int depth = 0;
void down() {
depth++;
down(); // no base case: recurse until the stack is full
}
void main() {
try {
down();
} catch (StackOverflowError e) {
IO.println("StackOverflowError, deeper than 10,000 calls: " + (depth > 10_000));
}
}$ java -Xss256k Depth.java
StackOverflowError, deeper than 10,000 calls: false
$ java -Xss16m Depth.java
StackOverflowError, deeper than 10,000 calls: truedown()calls itself forever. Each call pushes a frame onto the thread's stack, and nothing ever pops one.- With
-Xss256kthe stack is 256 KB. When it's full, the JVM throwsStackOverflowError. When this was written that took about 1,250 calls (the exact depth depends on frame sizes and on whether the JIT had compileddown()yet, so the program prints a stable comparison instead):deeper than 10,000 calls: false. - With
-Xss16mthe same code went more than 10,000 calls deep before failing:true. (About 340,000 here; the default 2 MB stack gave about 38,000.) StackOverflowErroris anError, not anException(chapter 06). Catching it here is only for the demonstration: by the time it's thrown, the stack is unwound back tomainand the frames are gone, so the program can carry on, but real code shouldn't rely on that.- In practice it almost always means unbounded recursion (a missing base case, two methods calling each other, a
toString()that prints an object which prints the first one back, a JPA entity graph serialised in a loop). Raising-Xssonly hides it; fix the recursion or make it a loop.
When the heap is full and the garbage collector can't free enough, the JVM throws OutOfMemoryError. Keep references to everything you allocate and you'll get there fast with a small heap:
void main() {
var keep = new ArrayList<byte[]>();
IO.println("max heap: " + Runtime.getRuntime().maxMemory() / (1024 * 1024) + " MB");
while (true) {
keep.add(new byte[1024 * 1024]); // 1 MB that stays reachable
}
}$ javac Fill.java
$ java -Xmx32m Fill
max heap: 32 MB
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at Fill.main(Fill.java:5)javac Fill.javacompiles the compact source file intoFill.class(running it withjava Fill.javaworks too, but then the stack trace also shows the source launcher's own frames).-Xmx32mcaps the heap at 32 MB, andRuntime.maxMemory()reports it:max heap: 32 MB.- Each loop adds a 1 MB array to a list that
mainstill holds, so nothing is garbage: every array is reachable throughkeep. - After about 30 arrays the heap is full. The GC runs, finds nothing to free, and the JVM throws
java.lang.OutOfMemoryError: Java heap spaceat the allocation,Fill.main(Fill.java:5). Nothing catches it, so the thread dies and the program exits with status 1. - The detail message tells you which memory ran out. Oracle's troubleshooting guide lists the main ones:
Java heap space(objects),Metaspace(class metadata, usually a class loader leak or a huge number of generated classes),GC overhead limit exceeded(the GC runs nearly all the time and frees almost nothing), andRequested array size exceeds VM limit.