Java Memory Model Demystified: Key Concepts and Usage
Abstract AlgorithmsTL;DR
TLDR: Java memory is split into two main areas: the Stack (for method execution) and the Heap (for objects). The Heap is further divided into Young Generation (Eden, Survivor) and Old Generation to optimize Garbage Collection. Understanding this stru...

TLDR: Java memory is split into two main areas: the Stack (for method execution) and the Heap (for objects). The Heap is further divided into Young Generation (Eden, Survivor) and Old Generation to optimize Garbage Collection. Understanding this structure helps you fix
OutOfMemoryErrorand tune performance.
1. What is the Java Memory Model? (The "No-Jargon" Explanation)
Imagine you are building a Lego castle.
The Workbench (The Stack): This is the small table right in front of you. You put the instructions and the specific blocks you are holding right now here. It's fast, easy to reach, but very small. When you finish a step, you clear it off.
The Storage Bin (The Heap): This is the giant box in the corner containing thousands of Lego pieces. It's huge and messy. When you build a castle tower, you put it here.
In Java:
Stack: Stores temporary variables and function calls.
Heap: Stores the actual Objects (The data).

2. The Stack Memory
What it stores: Local variables (
int x), method calls, and references to objects.Characteristics:
LIFO (Last In, First Out): Like a stack of plates.
Thread-Safe: Each thread has its own stack. They don't share.
Fast: Memory is automatically allocated and deallocated when a method finishes.
The Error:
StackOverflowError(Usually caused by infinite recursion).
3. The Heap Memory (Where Objects Live)
The Heap is where all your objects (new Person(), new String()) live. But it's not just one big bucket. Java organizes it based on Age. This is called the Generational Garbage Collection Hypothesis: Most objects die young.
The Structure of the Heap
| Zone | Sub-Zone | Description |
| Young Generation | Eden Space | The "Nursery". All new objects are created here. It's very active. |
| Young Generation | Survivor Spaces (S0, S1) | The "Kindergarten". Objects that survived one cleanup move here. |
| Old Generation | Tenured Space | The "Retirement Home". Objects that survived many cleanups live here (e.g., Caches, DB Connections). |
Deep Dive: The Journey of an Object (The Promotion Flow)
Objects don't just appear in the Old Generation. They have to "earn" their spot by surviving multiple garbage collection cycles. Here is the exact order of movement:
Creation (Eden):
new Object()is called. The object is allocated in the Eden space.Fate: If it dies here (e.g., a temporary variable inside a loop), it is removed instantly during the next Minor GC.
Survival (Eden $\rightarrow$ Survivor S0):
A Minor GC happens. The object is still alive (referenced).
It is moved from Eden to Survivor Space 0 (S0).
Age: 1.
Ping-Pong (Survivor S0 $\leftrightarrow$ Survivor S1):
Next Minor GC happens.
Alive objects in Eden and S0 are moved to Survivor Space 1 (S1). S0 is cleared.
Age: 2.
Note: In the next cycle, they move back from S1 to S0. They swap back and forth, aging each time.
Tenuring (Survivor $\rightarrow$ Old Generation):
Once the object reaches a specific age threshold (default is usually 15), it is considered "long-lived".
It is promoted (moved) to the Old Generation.
Retirement (Old Generation):
The object stays here until a Major GC runs.
Major GCs are infrequent because the Old Gen is large.
Deep Dive: How References Work (Stack vs. Heap)
This is the most important concept for Java developers. When you write Person p = new Person("Alice");, you are using both memories.
Toy Code Example
public void createPerson() {
int age = 25; // Primitive
Person p = new Person("Alice"); // Reference + Object
}
The "Black Box" Revealed: What's Inside Memory?
| Memory Area | Address/Location | Value Stored | Description |
| Stack | age | 25 | The actual value is here. |
| Stack | p | 0x55A1 | A Reference (Pointer) to the Heap. |
| Heap (Eden) | 0x55A1 | Person { name: "Alice" } | The actual Object data. |
The Logic:
Java sees
int age = 25. Sinceintis a primitive, it puts25directly on the Stack.Java sees
new Person("Alice"). It goes to the Heap (Eden), finds empty space at address0x55A1, and creates the object there.Java sees
Person p. It creates a variablepon the Stack and stores the address0x55A1in it.
4. Garbage Collection Mechanisms
How does Java actually clean the memory? It uses different algorithms depending on your needs.
A. Serial GC
How: Uses a single thread. Pauses the whole app to clean.
Use Case: Small, simple apps running on a laptop.
B. Parallel GC (Throughput Collector)
How: Uses multiple threads to clean the Young Gen quickly.
Use Case: Batch processing, Data analysis. Where raw speed matters more than pauses.
C. G1 GC (Garbage First) - The Standard
How: Splits the Heap into thousands of small regions. It cleans the regions with the most garbage first.
Use Case: Web Servers. It balances throughput with low pause times.
D. ZGC (Zero Pause GC)
How: The modern beast. It cleans memory while the app is running.
Use Case: Massive heaps (Terabytes) requiring <1ms pauses.
Real-World Application: The "Memory Leak"
In C++, a memory leak is when you forget to delete an object. In Java, the GC deletes objects for you. So, how can Java have memory leaks?
The Scenario: You have a static list that keeps growing.
public class Cache {
// Static means this lives in Metaspace/Heap forever!
public static List<String> history = new ArrayList<>();
public void addRequest(String req) {
history.add(req); // We keep adding, never removing.
}
}
The Problem: The GC looks at the Heap. It sees thousands of String objects. It asks, "Does anyone need these?"
The Answer: "Yes! The static list
historyon the Stack/Metaspace is pointing to them!"The Result: The GC cannot delete them. They eventually fill the Old Generation causing a fatal
OutOfMemoryError.
Summary & Key Takeaways
Stack: Fast, Thread-safe, stores Primitives & References.
Heap: Stores Objects. Divided into Eden (New), Survivor (Middle-aged), and Old Gen (Long-term).
GC: Moves objects from Eden -> Survivor -> Old Gen.
Tuning: If your app pauses too much, you might need to switch from Parallel GC to G1 GC or ZGC.
Practice Quiz: Test Your Knowledge
Scenario: You create a temporary object inside a loop
for(int i=0; i<1000; i++) { new Temp(); }. Where are these objects created, and what happens to them?A) Created in Old Gen; stay there forever.
B) Created in Eden; collected by Minor GC immediately.
C) Created on the Stack; deleted when loop ends.
Scenario: An object has survived 15 garbage collection cycles in the Survivor Space. Where does it go next?
A) Back to Eden.
B) To the Old Generation (Tenured Space).
C) It is deleted.
Scenario: You write
Person a = new Person("John"); Person b = a;. You then changeb.name = "Doe". What isa.name?A) "John" (Because
ais a separate copy).B) "Doe" (Because
aandbpoint to the same Heap object).
(Answers: 1-B, 2-B, 3-B)

Written by
Abstract Algorithms
@abstractalgorithms
