Memory Allocation in Java: Stack Memory vs Heap Space
JVM divides memory into stack and heap memory.
Whenever we declare a new variable/ object, or call a new method,
JVM allocates memory to these operations either from Heap Space or from Stack Memory.
Stack Memory in Java
Stack Memory in Java is used for static memory allocation and the execution of a thread.
- Stack is automatically allocated when a new method is called.
- Access to this memory is in Last-In-First-Out (LIFO) order.
- Stack contains method specific values
A new block on top of the stack stores values for this method: local primitive variables and reference variables to objects in heap space.
- Method specific values are short-lived.
Variables inside stack exist only as long as the method that created them is running.
- Stack is automatically deallocated when method finishes execution
After method execution is finished, it’s stack frame is flushed, the flow goes back to the calling method
and space becomes available for the next method.
- If stack memory is full, Java throws java.lang.StackOverFlowError
- Stack memory is threadsafe as each thread operates in its own stack
Heap Space in Java
Heap space in Java is used for dynamic memory allocation for Java objects and JRE classes at the runtime.
Whenever a new object is created, it’s always stored in the Heap space and stack memory contains the reference to it.
Any object created in the heap space has global access and can be referenced from anywhere of the application.
Heap Space memory model is further broken into smaller parts called generations:
- Young Generation
where all new objects are allocated and aged.
When objects are stored in the Young Generation, a threshold for the object’s age is set and when that threshold is reached, the object is moved to the old generation.
A minor Garbage Collection runs when this fills up to free the heap memory used by objects that don’t have any reference.
- Old or Tenured Generation
where long surviving objects are stored.
- Permanent Generation
consists of JVM metadata for the runtime classes and application methods
Stack vs Heap
- Because of simplicity in memory allocation (LIFO), access to stack memory is faster than to the heap memory.
- Stack memory size is much smaller than that of the Heap memory.
- Heap memory is used by all the parts of the application.
Stack memory is used only by one thread of execution.
- Whenever a new object is created, it’s always stored in the Heap space and stack memory contains only the reference to it.
- Objects stored in the heap are globally accessible whereas stack memory can’t be accessed by other threads.
- Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Generations and cleaned by Java Garbage Collection.
- Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.