JVM.MemoryManagement.What is the stack memory in JVM, and how does it differ from heap memory?

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

  1. 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 inside methodA() → 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

FeatureStack MemoryHeap Memory
StorageStores method call frames, local variables, and referencesStores objects and instance variables
AccessLIFO (Last-In-First-Out)Objects accessed dynamically
LifetimeExists only during method executionExists until Garbage Collection
Thread ScopeEach thread has its own stack (thread-local)Shared among all threads
SpeedFaster (direct access)Slower (needs GC and allocation)
Size LimitLimited (fixed per thread)Can grow dynamically
GC InvolvementNot managed by GCManaged 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.
This entry was posted in Без рубрики. Bookmark the permalink.