Memory Management
Deep dive into Java Memory Management, Stack vs Heap, and Garbage Collection.
Java Memory Management
Understanding how Java manages memory is crucial for writing efficient applications. Java memory is primarily divided into Stack and Heap.
Stack vs Heap
| Feature | Stack Memory | Heap Memory |
|---|---|---|
| Storage | Local variables, method calls | Objects, instance variables |
| Access | Fast access | Slower access |
| Size | Small, fixed size | Large, dynamic size |
| Lifetime | Cleared when method execution ends | Cleared by Garbage Collector |
Garbage Collection (GC)
Garbage Collection is the process of automatically identifying and discarding objects that are no longer in use to free up memory resources.
How it Works
- Mark: The GC identifies which pieces of memory are in use and which are not.
- Sweep: The GC removes objects identified during the "mark" phase.
- Compact: (Optional) Memory is compacted to prevent fragmentation.
Tip 💡
You can request garbage collection using System.gc(), but it is not
guaranteed to run immediately.
Common Memory Errors
1. StackOverflowError
Occurs when the stack memory is full, usually due to infinite recursion.
void recursive() {
recursive(); // Infinite loop -> StackOverflowError
}2. OutOfMemoryError (Heap Space)
Occurs when the heap memory is full, usually due to creating too many objects or memory leaks.
List<String> list = new ArrayList<>();
while (true) {
list.add("Memory Leak"); // Eventually -> OutOfMemoryError
}