Sub topic 2
Stack frames and the heap
This chapter covers how a running Java program splits its data between thread stacks and the shared heap, and why that split determines what the garbage collector manages. It assumes you can read basic Java, know that a variable can hold a reference to an object, and can run java and javac from a terminal. The previous chapter listed the runtime memory areas. This one looks at the two you meet most often.
Two places for two kinds of data
Every Java program stores data in two main places.
- The stack is a per-thread region that holds one frame for each method call currently in progress. Frames are created when a method is called and discarded when it returns.
- The heap is a single region shared by all threads. Every object and every array lives there, and the garbage collector reclaims it.
The two areas differ in lifetime. A frame lasts exactly as long as its method call. A heap object lasts as long as something can still reach it, which is the topic of the next chapter.
| Property | Thread stack | Heap |
|---|---|---|
| Scope | One per thread | One per JVM, shared by all threads |
| Holds | Frames: locals, parameters, intermediate values | Objects and arrays, including their fields and elements |
| Lifetime | Until the method returns | Until the object is unreachable and collected |
| Cleanup | Automatic on return (pop the frame) | Garbage collector |
| Overflow error | `StackOverflowError` | `OutOfMemoryError: Java heap space` |
| Size flag | `-Xss` | `-Xms`, `-Xmx` |
What a frame contains
A frame has three parts that matter here.
- Local variable array. It holds the method's parameters and local variables. For an instance method, slot 0 holds
this. Each slot holds either a primitive value (int,double,boolean, and so on) or a reference. - Operand stack. A small working area where bytecode instructions push and pop intermediate values. For
a + b, the JVM pushesa, pushesb, executes an add instruction, and leaves the result on this stack. - Frame data. Bookkeeping such as a link to the constant pool of the method's class and the information needed to return to the caller or unwind on an exception.
A reference is a small handle that identifies an object on the heap. On HotSpot it is usually a 4-byte compressed pointer when the heap is below about 32 GB. The reference sits in the frame. The object it points to sits on the heap.
So a local variable declared as Point p = new Point(1, 2); creates two things: the reference p in the current frame, and a Point object on the heap.
Pass by value, with references as the values
Java always passes arguments by value. For a primitive, the value is the number. For an object, the value is the reference. The callee gets its own copy of that reference in its own frame. Both copies point to the same heap object.
This has two consequences:
- Changes the callee makes through the reference (
p.x += 1) are visible to the caller, because there is only one object. - Reassigning the callee's parameter (
p = new Point(0, 0)) changes only the callee's copy of the reference. The caller's reference is untouched.
public class FrameDemo {
static class Point {
int x;
int y;
Point(int x, int y) { this.x = x; this.y = y; }
}
static void move(Point p, int dx) {
dx = dx + 1; // changes the callee's copy of the int
p.x += dx; // changes the shared heap object
p = new Point(0, 0); // changes only the callee's copy of the reference
}
public static void main(String[] args) {
Point pt = new Point(1, 2);
int d = 5;
move(pt, d);
System.out.println(pt.x + " " + d);
}
}The program prints 7 5. The x field changed from 1 to 7 (1 + 6) because move modified the shared object. The variable d is still 5 because move only changed its own copy.
When move returns, its frame is popped. The new Point(0, 0) created at the end is now unreferenced, so it is garbage. The original Point is still referenced by pt in main's frame.
Where each kind of variable lives
Beginners often say "primitives go on the stack and objects go on the heap". That is close but not exact. The precise rule is about where the variable is declared:
| Declaration | Where the variable lives | Where the value lives |
|---|---|---|
| Local `int n` | Frame of the current method | Same slot in the frame |
| Local `Point p` | Frame of the current method | Object on the heap |
| Field `int x` of an object | Inside the heap object | Same place |
| Static field | Class data, not a frame | Primitive inline, objects on the heap |
| Array `int[] a` | Reference in a frame or a field | Array object on the heap, with elements inside it |
| `Integer boxed` | Reference in a frame or a field | `Integer` object on the heap |
A primitive field inside an object is on the heap, because the whole object is. An int[] with a million elements is a single heap object of roughly 4 MB. It is not on the stack just because int is a primitive.
Stack limits and StackOverflowError
Each thread's stack has a fixed maximum size. HotSpot's default is typically 512 KB to 1 MB per thread, depending on platform, and -Xss changes it. If calls nest deeper than the stack can hold, the JVM throws StackOverflowError. Unbounded or very deep recursion is the usual cause.
public class DepthDemo {
private static int depth = 0;
static void recurse() {
depth++;
recurse();
}
public static void main(String[] args) {
try {
recurse();
} catch (StackOverflowError e) {
System.out.println("Depth reached: " + depth);
}
}
}The depth you see varies between runs, JVM versions, and whether the JIT compiler has optimized recurse. Try it with different stack sizes:
java DepthDemo
java -Xss256k DepthDemo
java -Xss4m DepthDemoA larger -Xss allows deeper recursion, but the setting applies to every thread you create. With 500 threads and -Xss4m, you reserve about 2 GB of address space for stacks. Raising -Xss is a fix for legitimate deep recursion, such as a recursive-descent parser on deeply nested input. For runaway recursion, fix the missing base case or convert the algorithm to a loop.
Stacks are not part of the heap. Heap flags such as -Xmx do not affect them, and a StackOverflowError does not mean the heap is full.
Why the stack is not a leak source
Frame memory is released as soon as a method returns, without garbage collection. For this reason a pure stack problem is never a "leak" in the usual sense. It is either too deep a call chain or too many threads.
The stack still affects the heap, because frames hold references. Those references are GC roots in the next chapter. An object referenced from a local variable in a running method cannot be collected. For example, a long-running main that holds a large list in a local variable keeps that list alive until the variable goes out of use.
The JIT compiler can treat a local as dead after its last use, even while the method is still running. The interpreter is more conservative. Don't rely on either behavior. If you want a large object collectable, remove every reference to it by setting the variable to null or by letting it go out of scope.
Does `new` always allocate on the heap?
By the language specification, yes: objects are heap objects. In practice, the HotSpot JIT compiler performs escape analysis. If it proves that an object never escapes the method that creates it (it is not stored in a field, returned, or passed somewhere it could be retained), it may apply scalar replacement. The object's fields become plain local values in registers or on the stack, and no heap allocation happens at all.
public class EscapeDemo {
static final class Vec {
final double x;
final double y;
Vec(double x, double y) { this.x = x; this.y = y; }
}
static double length(double x, double y) {
Vec v = new Vec(x, y); // never leaves this method
return Math.sqrt(v.x * v.x + v.y * v.y);
}
public static void main(String[] args) {
double sum = 0;
for (int i = 0; i < 200_000_000; i++) {
sum += length(i, i + 1);
}
System.out.println(sum);
}
}Compare GC activity with and without the optimization:
java -Xlog:gc EscapeDemo
java -XX:-DoEscapeAnalysis -Xlog:gc EscapeDemoOn a typical HotSpot JVM, the first run shows few or no GC events, because the Vec objects were eliminated after the JIT compiled length. The second run shows many young collections, because every call allocates a real object. Exact numbers depend on your JVM and hardware.
Common mistakes
- "Java passes objects by reference." It passes the reference by value. Reassigning a parameter never changes the caller's variable.
- Assuming a local variable's object is freed when the variable is reassigned elsewhere. The object is freed only when no reference to it remains, anywhere on any thread stack or in any heap object.
- Confusing the two memory errors.
StackOverflowErroris about call depth in one thread.OutOfMemoryError: Java heap spaceis about total live objects. - Sharing mutable heap objects between threads without synchronization. Each thread has its own stack, so locals are inherently thread-safe. The heap is shared, so any object reachable from two threads needs safe publication or synchronization. A local variable of a reference type protects only the reference, not the object it points to.
- Treating
-Xssas a heap setting. It sets the stack size for each new thread.
Summary of the model
Each thread owns a stack of frames. A frame holds primitives and references for one method call, and it vanishes when the call returns. Every object and array lives on the shared heap, and frames point to it through references. The collector's job begins where frames and other roots leave off: it finds which heap objects can still be reached and reclaims the rest.
Exercise
In the following code, which objects exist on the heap while helper is running, and which of them can be collected after helper returns? Assume helper is called from main.
static int helper() {
int[] data = new int[1000];
StringBuilder sb = new StringBuilder("x");
data[0] = sb.length();
return data[0];
}
Show answer
Two heap objects exist: the int[1000] array (about 4 KB of elements plus a header) and the StringBuilder (with its internal character buffer, which is a separate array object). The references data and sb live in helper's frame, and the primitive int return value is copied to the caller. When helper returns, its frame is popped and the references disappear. Nothing else refers to the array or the builder, so both become unreachable and the collector can reclaim them at its next cycle. The memory is not freed at the moment of return, only made eligible for collection.
Exercise
A method receives a List<String> names parameter and executes names = new ArrayList<>(); followed by names.add("a");. The caller passed in a list containing three names. What does the caller's list contain after the call, and why?
Show answer
It still contains the three original names. The assignment names = new ArrayList<>() only changes the method's own copy of the reference in its frame. The new list holds "a" and becomes garbage when the method returns. The caller's reference still points to the original list, which the method never modified. Had the method called names.add("a") without the reassignment, the caller's list would have four elements, because both references would point to the same heap object.
Exercise
A service throws StackOverflowError under heavy load, and a colleague proposes raising -Xmx from 2 GB to 8 GB. Explain why this will not help and name two things you could do instead.
Show answer
-Xmx sets the maximum heap size, but StackOverflowError means one thread's call stack exceeded its limit, which -Xss controls. A larger heap leaves the stack limit unchanged. Two options are: find and fix unbounded or excessively deep recursion (add a base case, or rewrite the algorithm iteratively with an explicit data structure), or, if the recursion depth is legitimate, raise -Xss for the JVM, remembering that it multiplies across all threads.