Card 05/ 09
StackOverflowError vs OutOfMemoryError
Both fatal, both about memory, and they point at opposite halves of the program.
StackOverflowError means one thread's stack (a thread is one path of execution, and its stack holds its chain of method calls) filled up, almost always from recursion that never stops. OutOfMemoryError means the heap (the memory where Java keeps every object) filled up with objects that are still reachable (still connected, through some chain of references, to a variable the program is using). Which one you got tells you where to look.
| Compared on | StackOverflowError | OutOfMemoryError |
|---|---|---|
| What ran out | One thread's stack | The heap |
| Caused by | Too many nested calls, usually unbounded recursion | Too many reachable objects |
| Time to failure | Seconds: the stack is small and fixed | Often hours or days of steady growth |
| The stack trace | Hundreds of identical frames (the JVM records at most 1024) | Ordinary, and at whatever line asked for memory |
| First thing to check | The base case of a recursive method | What is holding references it no longer needs |
static int countdown(int n) {
return countdown(n - 1);
}The decision rule for reading one. Look at the trace. Hundreds of repeating frames means the stack, and the fix is in the recursion. A trace that looks like any other, on a line that happens to allocate, means the heap, and the line in the trace is where the last straw landed rather than where the problem is.
← → move through sections and cards