Skip to main content
JVM tuning and diagnostics · Topic 2 of 5

The stack and StackOverflowError

Definition​

Every thread has its own stack that holds method calls and local variables. If calls nest too deeply, usually from a recursion that never stops, the stack runs out and Java throws StackOverflowError. The stack size is set with -Xss.

Example code​

A runaway recursion is caught

class Demo {
static int depth = 0;

static void recurse() {
depth++;
recurse(); // no stop condition: each call adds a frame to the stack
}

public static void main(String[] args) {
try {
recurse();
} catch (StackOverflowError e) {
System.out.println("stack ran out of space, reached a depth above 1000: " + (depth > 1000));
}
// a bigger stack for deep but valid recursion: java -Xss2m ...
}
}

// Output:
// stack ran out of space, reached a depth above 1000: true

Finished this page? Track your progress (saved only in your browser).