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

FeatureStack MemoryHeap Memory
StorageLocal variables, method callsObjects, instance variables
AccessFast accessSlower access
SizeSmall, fixed sizeLarge, dynamic size
LifetimeCleared when method execution endsCleared 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

  1. Mark: The GC identifies which pieces of memory are in use and which are not.
  2. Sweep: The GC removes objects identified during the "mark" phase.
  3. 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
}