Card 01/ 09

ConceptDifficulty: Intermediate1 min

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:

The two regions, what lives in each, and what clears them
Compared onThe stackThe heap
HoldsOne frame per method callEvery object created with new
Made ofFrames, each with parameters, local variables and where to return toObjects, each with its fields
ClearedWhen the method returnsBy the garbage collector, the part of the JVM that frees unused memory, when nothing can reach it
Per threadOne stack eachShared by all threads, the program's parallel paths of execution
SizeFixed, smallConfigurable, 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.