Stack memory in the JVM is used for storing method call frames, local variables, and intermediate computations. It is a private, thread-local memory allocated per thread when it starts.
How Stack Memory is Used
- Method Calls & Execution
- Each time a method is called, a new frame is pushed onto the thread’s stack.
- When the method returns, the frame is popped off the stack.Example:
void methodA() {
int x = 10; // Stored in stack
methodB();
}
void methodB() {
int y = 20; // Stored in stack
}
Execution:
methodA()
is called → a new stack frame is created.methodB()
is called insidemethodA()
→ another stack frame is created.- When
methodB()
returns, its frame is removed from the stack. - Finally,
methodA()
returns, and its frame is also removed.
Stores Local Variables
- Primitive types (
int
,double
, etc.) and references to objects are stored in the stack. - Actual objects are stored in the heap.
void example() {
int a = 5; // 'a' stored in stack
String str = "Hello"; // 'str' reference in stack, actual object in heap
}
Exception Handling
- If a method call stack overflows, a StackOverflowError occurs.
- Example:
void recursiveMethod() {
recursiveMethod(); // Infinite recursion → StackOverflowError
}
OutOfMemoryError (Heap space):
- Occurs when JVM can’t allocate more heap memory for objects.
List<Object> list = new ArrayList<>();
while (true) {
list.add(new Object()); // Leads to OutOfMemoryError (Heap)
}
Differences Between Stack Memory and Heap Memory
Feature | Stack Memory | Heap Memory |
---|---|---|
Storage | Stores method call frames, local variables, and references | Stores objects and instance variables |
Access | LIFO (Last-In-First-Out) | Objects accessed dynamically |
Lifetime | Exists only during method execution | Exists until Garbage Collection |
Thread Scope | Each thread has its own stack (thread-local) | Shared among all threads |
Speed | Faster (direct access) | Slower (needs GC and allocation) |
Size Limit | Limited (fixed per thread) | Can grow dynamically |
GC Involvement | Not managed by GC | Managed by GC |
Key Takeaways
- Stack is faster than Heap because of its direct memory access.
- Stack is thread-local, while Heap is shared across threads.
- Stack overflow occurs if recursion or deep method calls exceed its limit.
- Objects in heap live longer than local variables in the stack.