Card 01/ 09
The Stack and the Heap in Java
One program dies after four seconds of recursion, another after four hours of work, and they ran out of different things.
The JVM keeps a running program's data in two regions. The stack holds one frame per method call, with that call's parameters and local variables, and a frame disappears when its method returns. The heap holds every object created with new, and an object stays there until nothing can reach it.
Two failures look alike from the outside: a program that dies after four seconds of recursion, and one that dies after four hours of steady work. They exhaust different things, and telling them apart starts with knowing there are two regions with different rules:
| Compared on | The stack | The heap |
|---|---|---|
| Holds | One frame per method call | Every object created with new |
| Made of | Frames, each with parameters, local variables and where to return to | Objects, each with its fields |
| Cleared | When the method returns | By the garbage collector, the part of the JVM that frees unused memory, when nothing can reach it |
| Per thread | One stack each | Shared by all threads, the program's parallel paths of execution |
| Size | Fixed, small | Configurable, large |
Every object is on the heap, without exception. A local variable holding a List sits in the stack frame, the space on the stack for one method call; the list itself is on the heap, and the variable holds its address.
So a local int disappears the moment its method returns, and an object outlives the method that made it for as long as anything still points at it. That difference is what the rest of this topic is about.
← → move through sections and cards