Memory Management
Stack, Heap, Method Area, Garbage Collection, JVM memory model
- Map the complete JVM memory model
- Understand Stack vs Heap allocation
- Master garbage collection algorithms and triggers
- Diagnose memory leaks and optimize memory usage
*Java Basics to Advanced | Lecture 4*
Table of Contents
- Introduction to Java Memory Management
- Stack Memory
- Heap Memory
- Stack vs. Heap — Complete Comparison
- Memory in Action — Full Code Walkthrough
- Garbage Collector
- Types of Object References
- Making an Object Eligible for GC
- Heap Memory — Internal Structure
- Garbage Collection Algorithms
- Types of Garbage Collectors
- Summary Diagrams
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Quick Revision Summary
1. Introduction to Java Memory Management
Overview
When you write a Java program and run it, every variable, every object, every method call consumes RAM (Random Access Memory). Understanding how that memory is allocated, organized, and freed is one of the most important concepts for any Java developer — both for interviews and for writing efficient, production-quality code.
Who Manages Memory in Java?
JVM (Java Virtual Machine)
is entirely responsible for memory management in Java.
This is one of Java's key advantages over languages like C and C++, where the programmer must manually allocate and free memory (using malloc / free in C). In Java, memory is:
- Automatically allocated when you create variables and objects
- Automatically freed by the Garbage Collector when objects are no longer needed
This is why Java is described as having automatic memory management.
The Two Main Memory Areas
JVM divides the available RAM into two primary regions:
1┌─────────────────────────────────────────────────────────┐2│ JVM Memory │3│ │4│ ┌─────────────┐ ┌──────────────────────────┐ │5│ │ STACK │ │ HEAP │ │6│ │ (smaller) │ │ (larger) │ │7│ │ │ │ │ │8│ │ • Primitive │ │ • Objects │ │9│ │ values │ │ • String pool │ │10│ │ • References│ │ • Instance variables │ │11│ │ • Method │ │ │ │12│ │ frames │ │ │ │13│ └─────────────┘ └──────────────────────────┘ │14│ │15│ (one per thread) (one shared by all threads) │16└─────────────────────────────────────────────────────────┘2. Stack Memory
Definition
Stack memory
is a region of RAM where method frames, primitive values, and object references are stored. Each thread in a Java program has its own private stack.
What Gets Stored in Stack?
| Data Type | Stored In Stack? | Details |
|---|---|---|
Primitive variables (int, double, boolean, etc.) | ✅ Yes | Value stored directly |
| Object references | ✅ Yes | The reference (address/pointer) is stored; the object itself is in heap |
| Method frames | ✅ Yes | One frame per active method call |
| Local variables | ✅ Yes | All variables declared inside a method |
Key Characteristics of Stack
1. Temporary Variables
Variables in the stack exist only for the lifetime of the block they are declared in. Once execution leaves the block (}), the variable is destroyed.
2. Method Frames (Stack Frames)
Every time a method is called, JVM creates a new memory block (frame) on the stack for that method. This frame holds:
- All local variables of the method
- All object references created inside the method
- The method's parameters
3. Each Thread Has Its Own Stack
Since Java supports multithreading, every thread gets its own independent stack. Threads do not share stack memory.
1Thread 1 Stack Thread 2 Stack Thread 3 Stack2┌───────────┐ ┌───────────┐ ┌───────────┐3│ method B │ │ method D │ │ method F │4│───────────│ │───────────│ │───────────│5│ method A │ │ method C │ │ method E │6└───────────┘ └───────────┘ └───────────┘7 All share one common Heap4. LIFO Order Last In, First Out
The stack operates on the LIFO principle. The last method called is the first one to finish and be removed from the stack (like a stack of plates — you remove the top one first).
5. Variable Scope
Variables in the stack are only accessible within their own scope (their own method frame). A variable in method B cannot be directly accessed from method A.
6. Stack Overflow Error
If too many method frames are pushed onto the stack (e.g., infinite recursion), the stack runs out of space and you get:
1java.lang.StackOverflowError3. Heap Memory
Definition
Heap memory
is the region of RAM where all Java objects are stored. It is shared by all threads and is managed by the Garbage Collector.
What Gets Stored in Heap?
| Data Type | Stored In Heap? | Details |
|---|---|---|
Objects (created with new) | ✅ Yes | Full object data stored here |
| String literals | ✅ Yes | In the String Pool (a special area inside heap) |
| Instance variables | ✅ Yes | Stored as part of the object |
| Arrays | ✅ Yes | Arrays are objects in Java |
Key Characteristics of Heap
- Larger than stack memory
- One shared heap per JVM instance — all threads access the same heap
- Objects live until they are garbage collected
- Managed by the Garbage Collector
- Running out of heap memory causes:
java.lang.OutOfMemoryError
4. Stack vs. Heap Complete Comparison
| Feature | Stack | Heap |
|---|---|---|
| What it stores | Primitives, references, method frames | Objects, arrays, String pool |
| Size | Smaller | Larger |
| Number | One per thread | One shared for all threads |
| Access speed | Faster | Slower (relative) |
| Memory management | Automatic — variables removed when scope ends | Garbage Collector |
| Thread safety | Thread-safe (private to each thread) | Shared — requires synchronization |
| Lifetime | Until method/block ends | Until no references remain (GC cleans up) |
| Error when full | StackOverflowError | OutOfMemoryError |
| Order | LIFO (Last In, First Out) | No particular order |
5. Memory in Action Full Code Walkthrough
The Code
1public class MemoryManagement {2
3 public static void main(String[] args) {4 int primitiveVariable = 10; // line 15 Person personObj = new Person(); // line 26 String stringLiteral = "24"; // line 37 MemoryManagement memObj = new MemoryManagement(); // line 48 memObj.memoryManagementTest(personObj); // line 59 }10
11 public void memoryManagementTest(Person personObj) {12 Person personObj2 = personObj; // line 613 String stringLiteral2 = "24"; // line 714 String stringLiteral3 = new String("24"); // line 815 } // line 9 — method ends16} // line 10 — main endsStep-by-Step Memory Trace
Initial State
Stack and Heap are both empty.
1STACK HEAP2┌─────────┐ ┌─────────────────────────────┐3│ (empty) │ │ (empty) │4└─────────┘ └─────────────────────────────┘Step 1: `main()` is called
JVM creates a new frame on the stack for the main method.
1STACK HEAP2┌──────────────┐ ┌──────────────────────────────┐3│ main frame │ │ (empty) │4└──────────────┘ └──────────────────────────────┘Step 2: Line 1 `int primitiveVariable = 10`
A primitive variable. Its value is stored directly on the stack inside the main frame.
1STACK HEAP2┌──────────────────┐ ┌──────────────────────────────┐3│ main frame │ │ (empty) │4│ primitiveVar=10 │ │ │5└──────────────────┘ └──────────────────────────────┘Step 3: Line 2 `Person personObj = new Person()`
- A Person object is created in the heap
- A reference (
personObj) pointing to that heap object is stored on the stack
1STACK HEAP2┌───────────────────┐ ┌────────────────────────────┐3│ main frame │ │ [Person Object] │4│ primitiveVar=10 │ │ (memory address: 0x100) │5│ personObj → ─────┼───┼──► │6└───────────────────┘ └────────────────────────────┘Step 4: Line 3 `String stringLiteral = "24"`
- String literals are stored in the String Pool (inside heap)
- String Pool first checks: is
"24"already in the pool? No → creates it - A reference (
stringLiteral) is stored on the stack pointing to the pool entry
1STACK HEAP2┌──────────────────┐ ┌───────────────────────────────────┐3│ main frame │ │ [Person Object @ 0x100] │4│ primitiveVar=10 │ │ │5│ personObj → ────┼─────┼──► │6│ stringLiteral──►│ │ String Pool: ["24" @ 0x200] │7└──────────────────┘ └───────────────────────────────────┘Step 5: Line 4 `MemoryManagement memObj = new MemoryManagement()`
- A MemoryManagement object is created in the heap
- Its reference (
memObj) is stored on the stack
Step 6: Line 5 `memObj.memoryManagementTest(personObj)` called
A new frame for memoryManagementTest is pushed on top of the main frame (LIFO).
1STACK2┌────────────────────────────────────┐3│ memoryManagementTest frame │ ← TOP (most recent)4│ (parameters and locals go here) │5├────────────────────────────────────┤6│ main frame │7│ primitiveVar=10 │8│ personObj → (heap @ 0x100) │9│ stringLiteral → (pool "24") │10│ memObj → (heap @ 0x300) │11└────────────────────────────────────┘12
13HEAP14┌──────────────────────────────────────────┐15│ [Person Object @ 0x100] │16│ [MemoryManagement Object @ 0x300] │17│ String Pool: ["24" @ 0x200] │18└──────────────────────────────────────────┘Step 7: Line 6 `Person personObj2 = personObj` (inside test method)
- No new object is created in heap
personObj2is a new reference in the stack frame, pointing to the same heap object aspersonObj
1STACK (memoryManagementTest frame)2┌───────────────────────────────────────┐3│ personObj → (heap @ 0x100) │ ← passed in as parameter4│ personObj2 → (heap @ 0x100) │ ← same object, second reference5└───────────────────────────────────────┘Two references, one object. No duplication in heap.
Step 8: Line 7 `String stringLiteral2 = "24"` (inside test method)
- String Pool already has
"24"(created in Step 4) stringLiteral2simply points to the same existing pool entry- No new String object created
1stringLiteral (main frame) → String Pool "24" @ 0x2002stringLiteral2 (test frame) → String Pool "24" @ 0x200 ← SAME pool entryStep 9: Line 8 `String stringLiteral3 = new String("24")` (inside test method)
- The
newkeyword forces a new object to be created in the heap (outside String Pool) - Even though the value
"24"already exists in the pool, a brand-new String object is created stringLiteral3points to this new heap object
1HEAP2┌──────────────────────────────────────────┐3│ [Person Object @ 0x100] │4│ [MemoryManagement Object @ 0x300] │5│ [String Object "24" @ 0x400] │ ← new, NOT in pool6│ String Pool: ["24" @ 0x200] │7└──────────────────────────────────────────┘Step 10: Line 9 Closing `}` of `memoryManagementTest`
The method's scope ends. The entire memoryManagementTest frame is popped from the stack (LIFO). All references in that frame are destroyed.
Removed from stack:
personObj(reference) — gonepersonObj2(reference) — gonestringLiteral2(reference) — gonestringLiteral3(reference) — gone
Still in heap (orphaned — no references):
- String Object
"24" @ 0x400— no reference left → eligible for GC
1STACK (only main frame remains)2┌───────────────────────────────────┐3│ main frame │4│ primitiveVar=10 │5│ personObj → (heap @ 0x100) │6│ stringLiteral → (pool "24") │7│ memObj → (heap @ 0x300) │8└───────────────────────────────────┘Step 11: Line 10 Closing `}` of `main`
main frame is also popped. All its references are destroyed.
Stack is now empty.
In heap — all objects are now unreferenced:
- Person Object @ 0x100 — eligible for GC
- MemoryManagement Object @ 0x300 — eligible for GC
- String Object "24" @ 0x400 — eligible for GC
- String Pool "24" @ 0x200 — eligible for GC (if no other references)
What About the Heap Objects?
The stack references are gone, but the heap objects remain until the Garbage Collector runs and frees them.
Complete Memory Flow Diagram
6. Garbage Collector
Definition
The Garbage Collector (GC) is a background process managed by JVM that automatically identifies and removes objects in heap that have no active references, freeing that memory for future use.
Why GC Exists
Without GC, heap memory would fill up with abandoned objects and eventually cause the program to crash (OutOfMemoryError). GC eliminates the need for manual memory management.
When Does GC Run?
GC is controlled entirely by JVM. You cannot force it to run on demand.
1System.gc(); // Suggests to JVM: "Please run GC now"System.gc() is a suggestion, not a command. JVM may choose to ignore it. There is no guarantee that calling System.gc() will actually trigger garbage collection.JVM decides when to run GC based on:
- How full the heap is
- Memory allocation rate
- Application pause time goals
If the heap fills up fast, GC runs more frequently. If there is plenty of space, GC may run rarely.
What Makes an Object Eligible for GC?
An object becomes eligible for garbage collection when there are no more active references pointing to it from the stack (or from other reachable objects).
Stop-the-World Pause
This is why GC algorithm design is critical — minimizing pause times directly improves application throughput and latency.
1Application threads: ─────────────╗ ╔─────────────────────────2 ↓ ↑3GC thread: ╔══╝ (GC completes)4 [ PAUSE - App threads stopped ]7. Types of Object References
Java provides four types of references, which differ in how aggressively the Garbage Collector will collect the referenced object.
7.1 Strong Reference
The default type of reference. As long as a strong reference to an object exists, the GC will never collect that object.
1Person pObj = new Person(); // Strong reference2// GC will NOT delete the Person object as long as pObj exists and is reachableLifecycle: Object lives as long as the strong reference is reachable.
7.2 Weak Reference
An object with only a weak reference will be collected by GC the next time GC runs, regardless of whether memory is scarce.
1import java.lang.ref.WeakReference;2
3WeakReference<Person> weakPObj = new WeakReference<>(new Person());4
5// Access the object (before GC runs)6Person p = weakPObj.get(); // may return the object7
8// After GC runs9System.gc();10Person pAfterGC = weakPObj.get(); // returns null — object was collectedLifecycle: Object lives until the next GC cycle. After GC runs, get() returns null.
Common use case: WeakHashMap — used for caches where entries should be evicted when no longer strongly referenced.
7.3 Soft Reference
Similar to weak reference, but GC will not collect the object unless it urgently needs memory (i.e., heap is nearly full).
1import java.lang.ref.SoftReference;2
3SoftReference<Person> softPObj = new SoftReference<>(new Person());4
5// GC runs — if memory is fine, object is kept alive6// GC runs — if memory is critically low, object is collected7Person p = softPObj.get(); // may be null if GC cleared itLifecycle: Object may survive multiple GC cycles until heap pressure is high enough to force eviction.
Common use case: Memory-sensitive caches — the cache grows when memory is plentiful, shrinks automatically under memory pressure.
7.4 Phantom Reference
The weakest reference type. Used for post-mortem cleanup — you are notified after an object is collected but before its memory is reclaimed.get()always returnsnull.
1import java.lang.ref.PhantomReference;2import java.lang.ref.ReferenceQueue;3
4ReferenceQueue<Person> queue = new ReferenceQueue<>();5PhantomReference<Person> phantomRef = new PhantomReference<>(new Person(), queue);6
7// phantomRef.get() always returns null8// Used for finalization and resource cleanupCommon use case: Advanced resource cleanup (e.g., closing native resources after an object is GC'd).
Reference Types Comparison
| Reference Type | GC Behavior | get() after GC | Use Case |
|---|---|---|---|
| Strong | Never collected while reachable | Object still there | Default — all normal usage |
| Weak | Collected at next GC run | Returns null | WeakHashMap, canonical maps |
| Soft | Collected only under memory pressure | May return null | Memory-sensitive caches |
| Phantom | Always collected; notified post-mortem | Always null | Resource cleanup, finalization |
8. Making an Object Eligible for GC
There are several ways to remove all strong references from an object, making it eligible for garbage collection.
Method 1: Assign `null` to the Reference
1Person personObj = new Person();2// personObj → [Person Object in heap]3
4personObj = null;5// personObj now holds null — no reference to Person object6// Person object is now eligible for GCMethod 2: Reassign the Reference to Another Object
1Person obj1 = new Person(); // obj1 → [Person Object 1]2Person obj2 = new Person(); // obj2 → [Person Object 2]3
4obj1 = obj2;5// obj1 now points to Person Object 26// Person Object 1 has no references → eligible for GCMethod 3: Reference Goes Out of Scope
1public void someMethod() {2 Person p = new Person(); // p → [Person Object]3 // ... use p ...4} // p goes out of scope — stack frame destroyed5 // Person Object has no references → eligible for GCMethod 4: All References Pointing to an Object Are Removed
1Person obj1 = new Person();2Person obj2 = obj1; // two references to same object3
4obj1 = null; // one reference removed — object NOT yet eligible5obj2 = null; // last reference removed — NOW eligible for GC9. Heap Memory Internal Structure
The heap is not a flat, undivided block of memory. JVM divides it into regions, each with a specific purpose and GC strategy.
Overview
1┌─────────────────────────────────────────────────────────────────────┐2│ HEAP MEMORY │3│ │4│ ┌────────────────────────────────────┐ ┌─────────────────────┐ │5│ │ YOUNG GENERATION │ │ OLD GENERATION │ │6│ │ │ │ (Tenured) │ │7│ │ ┌──────────┐ ┌────┐ ┌────┐ │ │ │ │8│ │ │ EDEN │ │ S0 │ │ S1 │ │ │ Long-lived │ │9│ │ │ │ │ │ │ │ │ │ objects │ │10│ │ │ New objs │ │Surv│ │Surv│ │ │ │ │11│ │ │ created │ │ivor│ │ivor│ │ │ │ │12│ │ └──────────┘ └────┘ └────┘ │ │ │ │13│ └────────────────────────────────────┘ └─────────────────────┘ │14└─────────────────────────────────────────────────────────────────────┘15
16┌──────────────────────────────────────────┐17│ META SPACE (NON-HEAP — outside heap) │18│ Class metadata, static vars, constants │19└──────────────────────────────────────────┘9.1 Young Generation
All newly created objects start their life in the Young Generation. The GC that operates here is called Minor GC — it runs frequently and is fast.
Young Generation is divided into three areas:
Eden Space
- Every new object is first allocated in Eden
- When Eden fills up, Minor GC is triggered
Survivor Spaces (S0 and S1)
- Two equal-sized spaces: S0 and S1
- At any given time, one is in use and the other is empty
- Objects that survive GC are moved between S0 and S1 alternately
- Each time an object survives a GC cycle, its age increases by 1
Minor GC Step by Step
Let's trace through multiple GC cycles:
◆ Initial State: 5 objects created in Eden
1Eden: [O1] [O2] [O3] [O4] [O5]2S0: (empty)3S1: (empty)4Old: (empty)◆ Minor GC #1 runs
Mark: O2 and O5 have no references — mark for deletion Sweep: Delete O2, O5. Move survivors to S0, increment age.
1Eden: (empty — freed)2S0: [O1 age=1] [O3 age=1] [O4 age=1]3S1: (empty)4Old: (empty)◆ More objects created: O6, O7 in Eden
1Eden: [O6] [O7]2S0: [O1 age=1] [O3 age=1] [O4 age=1]3S1: (empty)4Old: (empty)◆ Minor GC #2 runs
Mark: O4 and O7 have no references Sweep: Delete O4, O7. Move survivors — this time to S1 (alternating). Age increases.
1Eden: (empty)2S0: (empty — freed)3S1: [O6 age=1] [O1 age=2] [O3 age=2]4Old: (empty)◆ More objects: O8, O9 in Eden
1Eden: [O8] [O9]2S1: [O6 age=1] [O1 age=2] [O3 age=2]◆ Minor GC #3 runs (threshold = age 3)
Mark: O9 has no reference Sweep: Delete O9. Move survivors to S0. Ages increase. O1 now reaches age 3 = threshold → PROMOTED to Old Generation
1Eden: (empty)2S0: [O8 age=1] [O6 age=2] [O3 age=3→promoted]3S1: (empty)4Old: [O1] ← PROMOTEDPromotion Rule
When an object's age reaches the threshold (configurable, default is typically 15 in HotSpot JVM), it is promoted from Young Generation to Old Generation.
The age threshold can be set with JVM flag: -XX:MaxTenuringThreshold=N
9.2 Old Generation (Tenured)
Characteristics
- Holds long-lived objects that have survived many GC cycles in Young Generation
- GC here is called Major GC (or Full GC)
- Major GC runs much less frequently than Minor GC
- Major GC is more time-consuming because:
- Objects here have many references pointing to them
- Objects may reference other objects (complex object graphs)
- The region is typically larger
Why Is Major GC Slower?
Objects in the old generation have survived many GC cycles, which means:
- There are likely many references to them from across the application
- They may hold references to many other objects
- Traversing and marking these complex reference graphs takes more time
9.3 Meta Space
What Is It?
Meta Space
is a non-heap memory area (outside the heap) where JVM stores class-level metadata.
What Does Meta Space Store?
| Data | Description |
|---|---|
| Class metadata | Information about loaded classes (name, methods, fields) |
| Static (class) variables | Variables declared with static — belong to the class, not objects |
| Constants | Values declared static final |
| Method bytecode | The compiled instructions of methods |
Meta Space vs. PermGen (Historical Context)
java.lang.OutOfMemoryError: PermGen space.
From Java 8 onwards, PermGen was replaced by Meta Space, which is outside the heap and dynamically expandable — it grows automatically as needed.| Feature | PermGen (before Java 8) | Meta Space (Java 8+) |
|---|---|---|
| Location | Part of heap | Outside heap (native memory) |
| Size | Fixed | Dynamically expandable |
| Error when full | OutOfMemoryError: PermGen space | OutOfMemoryError: Metaspace (rare) |
| Stores | Same type of class data | Same type of class data |
Complete Heap + Meta Space Diagram
10. Garbage Collection Algorithms
Mark and Sweep
The foundational GC algorithm. It operates in two phases:
Phase 1: Mark
GC traverses all reachable objects starting from GC roots (stack references, static references). Every reachable object is marked as alive. Unmarked objects are candidates for deletion.
1Before Mark:2Heap: [O1✓] [O2?] [O3✓] [O4?] [O5✓]3 ↑ no ref ↑ no ref4
5After Mark:6Marked alive: O1, O3, O57Marked for deletion: O2, O4Phase 2: Sweep
All objects not marked (unreachable) are deleted, and their memory is freed.
1After Sweep:2Heap: [O1] [ ] [O3] [ ] [O5]3 ↑freed ↑freed4(fragmented memory)Mark and Sweep with Compaction
Adds a third Compaction phase after sweep to eliminate memory fragmentation.
Phase 3: Compact
Surviving objects are moved together (compacted), leaving a contiguous free block at the end.
1After Compact:2Heap: [O1] [O3] [O5] [ FREE ]Benefits of compaction:
- Eliminates fragmentation
- New objects can be allocated quickly (just move the pointer)
- Better cache performance (objects are contiguous)
Drawback:
- Compaction requires moving objects, which means updating all references to those objects — expensive
11. Types of Garbage Collectors
Java offers multiple GC implementations, each with different trade-offs between throughput (work done per unit time) and pause time (Stop-the-World duration).
Overview Comparison
| GC Type | GC Threads | Pause Time | Compaction | Best For |
|---|---|---|---|---|
| Serial GC | 1 thread | Long | Yes | Single-core, small apps |
| Parallel GC | Multiple | Medium | Yes | Throughput-focused (Java 8 default) |
| CMS (Concurrent Mark Sweep) | Concurrent | Short (mostly) | No | Low-latency apps |
| G1 GC | Concurrent + Parallel | Very short | Yes | Balanced (Java 9+ default) |
11.1 Serial GC
1GC Thread: ═══════════════════════════2App Threads: ────────╗ ╔──────3 │ PAUSE (long) │4 └───────────────┘- Only one GC thread does all the cleanup work
- All application threads are paused for the entire duration
- Slow — single-threaded is inherently slower
- Simple — minimal overhead, good for tiny applications or single-core systems
Enable with: -XX:+UseSerialGC
11.2 Parallel GC *(Java 8 default)*
1GC Thread 1: ════════════2GC Thread 2: ════════════ (parallel)3GC Thread 3: ════════════4App Threads: ────────╗ ╔────────────5 │PAUSE│ (shorter)6 └─────┘- Multiple GC threads work in parallel (count depends on CPU cores)
- Application threads still paused during GC, but for a shorter time
- Higher throughput than Serial GC
- Still has Stop-the-World pause — just shorter
Enable with: -XX:+UseParallelGC Set thread count: -XX:ParallelGCThreads=N
11.3 Concurrent Mark Sweep (CMS)
1App Threads: ─────────────────────────────────────────2GC Thread: ────────╗ ╔══════════════╗ ╔════╗ ╔──────3 │ │ concurrent │ │ │ │4 │ │ GC work │ │ │ │5 ╚═╝ ╚═╝ ╚═╝6 (tiny (most work (tiny (tiny7 pause) concurrent) pause) pause)- GC threads run concurrently with application threads — most GC work happens without stopping the app
- Application threads are paused for very short periods (only during initial mark and re-mark phases)
- No compaction — memory can become fragmented over time
Drawbacks:
- No compaction → fragmentation can lead to
OutOfMemoryErroreven with free memory - GC uses CPU cycles concurrently → reduces CPU available to the application
- Not 100% guaranteed to avoid Stop-the-World pauses
Enable with: -XX:+UseConcMarkSweepGC
11.4 G1 GC (Garbage First) *(Java 9+ default)*
1Heap divided into equal regions:2┌───┬───┬───┬───┬───┬───┬───┬───┐3│ E │ S │ O │ E │ S │ O │ E │ F │ E=Eden, S=Survivor, O=Old, F=Free4└───┴───┴───┴───┴───┴───┴───┴───┘5GC targets regions with MOST garbage first (hence "Garbage First")- Divides heap into equal-sized regions (not contiguous Eden/Old/Survivor areas)
- GC prioritizes regions with the most garbage first
- Runs concurrently AND in parallel
- Does compaction — avoids fragmentation
- Designed for low-pause, predictable GC
- Allows setting pause time goals:
-XX:MaxGCPauseMillis=200
Enable with: -XX:+UseG1GC
GC Evolution Timeline
Impact on Application Performance
Throughput
= amount of work your application completes per unit time Latency = time taken to respond to a single request
When GC pauses are reduced:
- App threads pause less → more time processing requests
- Throughput increases (e.g., from 1000 to 1500 requests/minute)
- Latency decreases (faster response times)
12. Summary Diagrams
Complete JVM Memory Architecture
Object Lifecycle
13. Common Mistakes
Mistake 1: Thinking `System.gc()` Forces GC
1System.gc(); // ❌ Does NOT guarantee GC will runSystem.gc() is merely a request to the JVM. JVM has the final say. Never write code that depends on GC running at a specific time.Mistake 2: Thinking Objects Are Immediately Deleted When References Are Removed
1Person p = new Person();2p = null; // Object is ELIGIBLE for GC, but NOT immediately deletedThe object stays in heap until the Garbage Collector runs (which JVM controls).
Mistake 3: Confusing Stack Overflow with Out of Memory
| Error | Cause | Memory Area |
|---|---|---|
StackOverflowError | Too many nested method calls (stack is full) | Stack |
OutOfMemoryError | Too many objects, GC cannot free enough (heap is full) | Heap |
Mistake 4: String Literal vs. String Object
1String s1 = "hello"; // String Pool (heap) — may be shared2String s2 = "hello"; // Points to SAME pool entry as s13String s3 = new String("hello");// NEW object in heap (NOT pool)4
5System.out.println(s1 == s2); // true (same pool reference)6System.out.println(s1 == s3); // false (different heap objects)7System.out.println(s1.equals(s3)); // true (same content)Mistake 5: Assuming JVM is Platform-Independent for GC Behavior
GC behavior (timing, algorithms used) can vary between JVM implementations (HotSpot, OpenJ9, GraalVM) and can be tuned with JVM flags. Never assume specific GC timing in application code.
Mistake 6: Holding Unnecessary References (Memory Leak Pattern)
1public class MyCache {2 static List<Object> cache = new ArrayList<>(); // static = lives forever3
4 public void addToCache(Object obj) {5 cache.add(obj); // Objects added here are NEVER eligible for GC6 // (static list holds strong references)7 }8}This is a common memory leak pattern in Java — static collections holding strong references prevent GC from freeing objects.
14. Best Practices
- Let JVM manage memory — don't try to control GC manually with
System.gc(). - Nullify references you no longer need — especially in long-lived collections or static fields.
- Prefer local variables over instance/static variables — local variables are cleaned up automatically when method ends.
- Avoid memory leaks — be careful with static collections; always remove entries when no longer needed.
- Use
try-with-resourcesfor I/O and database resources — ensures they are closed even if an exception occurs. - Profile before optimizing — use tools like VisualVM, JProfiler, or Java Mission Control to identify actual memory issues.
- Set JVM heap size appropriately —
-Xms(initial heap) and-Xmx(max heap) should be tuned for your application. - Choose the right GC algorithm — for low-latency apps use G1 or ZGC; for batch/throughput apps use Parallel GC.
- Understand the difference between
==and.equals()for Strings — especially given String Pool behavior. - Use weak/soft references for caches — allows GC to reclaim memory when needed, preventing
OutOfMemoryError.
15. Interview Notes
Commonly Asked Questions
Q1: What are the two types of memory JVM uses? What does each store?
Answer:
- Stack — stores method frames, local variables, primitive values, and object references. One per thread. LIFO.
- Heap — stores all objects and arrays. One shared heap. Managed by Garbage Collector.
Q2: What is the difference between Stack and Heap?
Answer: Stack is smaller, faster, thread-private, and stores primitives and references. Heap is larger, shared by all threads, stores actual objects, and is managed by GC.
Q3: What is the Garbage Collector? When does it run?
Answer: GC is a JVM-managed background process that automatically frees heap memory by collecting objects with no active references. JVM decides when to run it — it runs periodically and more frequently when heap is under pressure. System.gc() only requests GC, does not guarantee it.
Q4: Explain the heap structure Young Generation, Old Generation, Meta Space.
Answer:
- Young Generation — new objects start here (Eden → Survivor S0/S1). Minor GC runs frequently here.
- Old Generation (Tenured) — objects promoted after surviving age threshold. Major GC runs less frequently.
- Meta Space (non-heap) — stores class metadata, static variables, constants. Replaced PermGen in Java 8. Expandable.
Q5: What is Minor GC vs. Major GC?
Answer:
- Minor GC — collects Young Generation (Eden + Survivors). Fast, frequent.
- Major GC — collects Old Generation. Slow, infrequent, more Stop-the-World pause.
Q6: What is the Mark and Sweep algorithm?
Answer: Two phases:
- Mark — traverse all reachable objects from GC roots and mark them as alive. Unmarked objects are garbage.
- Sweep — delete all unmarked (unreachable) objects and free their memory.
Compaction (optional third phase) — moves surviving objects together to eliminate fragmentation.
Q7: What is Stop-the-World?
Answer: When GC runs, all application threads are paused — this is called a Stop-the-World event. The application cannot process requests during this time. Minimizing pause time is a key goal of GC optimization.
Q8: What are the types of references in Java?
Answer:
- Strong — default; GC never collects while reference exists
- Weak — GC collects at next run regardless of memory pressure
- Soft — GC collects only under memory pressure
- Phantom — GC always collects; used for post-mortem cleanup
Q9: What is the difference between PermGen and Meta Space?
Answer: PermGen was part of the heap (before Java 8), had a fixed size, and caused OutOfMemoryError: PermGen space when full. Meta Space (Java 8+) is outside the heap (native memory), dynamically expandable, and stores the same type of class metadata.
Q10: What are the different GC algorithms/types?
Answer:
- Serial GC — single thread, long pauses, for small apps
- Parallel GC — multi-thread, shorter pauses, Java 8 default
- CMS — concurrent (most work while app runs), no compaction
- G1 GC — concurrent + parallel + compaction, low-pause, Java 9+ default
Q11: How does an object move from Young to Old Generation?
Answer: Each time an object survives a Minor GC, its age increments. When its age reaches the tenuring threshold (default 15 in HotSpot, configurable), it is promoted to Old Generation.
Q12: What error do you get when the stack is full? When the heap is full?
Answer:
- Stack full:
java.lang.StackOverflowError(usually from infinite recursion) - Heap full:
java.lang.OutOfMemoryError
16. Practice Questions
Easy
- What are the two main memory areas in Java? Which is larger?
- What kind of data is stored in stack? What kind in heap?
- What does LIFO mean? How does it apply to the stack?
- What error occurs when the stack is full? When the heap is full?
- What is the Garbage Collector and what does it do?
- Can you force the GC to run by calling
System.gc()? Explain. - What is the String Pool? Where is it located?
Medium
- Trace through the memory allocation for this code:
1 public static void main(String[] args) {2 int x = 5;3 String s = "hello";4 Person p = new Person("Alice");5 }Show what is in stack and heap after each line.
- What is the difference between a strong reference and a weak reference?
- Explain Minor GC vs. Major GC — when each runs and what each collects.
- Describe the Mark and Sweep algorithm. What is the role of compaction?
- Why does each thread have its own stack, but they share a single heap?
- What is the difference between PermGen and Meta Space? Why was PermGen replaced?
- What is the "Stop-the-World" event? Why does it matter for application performance?
Hard
- Trace the full memory lifecycle (stack + heap + GC) for the complete
MemoryManagementcode example from this lecture. At each step, show what is in stack, what is in heap, and what becomes eligible for GC. - Explain object promotion in detail: from Eden → Survivor → Old Generation, with age tracking. What is the default age threshold in HotSpot JVM?
- Compare Serial GC, Parallel GC, CMS, and G1 GC on the dimensions of: thread count, pause time, compaction, and best use case.
- You have a Java application that processes millions of short-lived objects per second. Which GC algorithm would you choose and why? What JVM flags would you consider?
- What is a memory leak in Java (given that GC exists)? Write a code example that creates a memory leak and explain how to fix it.
- Given
Person obj1 = new Person(); Person obj2 = obj1; obj1 = null;— is the Person object eligible for GC? Explain. What ifobj2 = nullis also added?
17. Quick Revision Summary
1☕ JAVA MEMORY MANAGEMENT — KEY POINTS2
3🗂️ TWO MEMORY AREAS:4 Stack → primitives, references, method frames5 one per thread | LIFO | faster | smaller6 full = StackOverflowError7 Heap → all objects, String Pool8 shared by all threads | managed by GC9 full = OutOfMemoryError10
11📦 WHAT GOES WHERE:12 int a = 10 → value stored in STACK13 new Person() → object in HEAP, reference in STACK14 String s = "hello" → reference in STACK, value in STRING POOL (HEAP)15 new String("hello") → NEW object in HEAP (not pool!)16 static int x → META SPACE17
18🗑️ GARBAGE COLLECTOR:19 • Removes unreferenced objects from heap20 • JVM controls when it runs — System.gc() is only a request21 • When GC runs → all app threads PAUSE (Stop-the-World)22 • Algorithm: Mark (find garbage) → Sweep (delete) → Compact (optional)23
24🏗️ HEAP STRUCTURE:25 Young Generation:26 Eden → new objects born here27 S0, S1 → survivors alternate; age++ each GC28 Old Generation (Tenured):29 → promoted when age >= threshold (default 15)30 → Major GC runs here (slower, less frequent)31 Meta Space (NON-HEAP):32 → class metadata, static vars, constants33 → replaced PermGen in Java 8; expandable34
35🔗 REFERENCE TYPES:36 Strong → GC never collects (default usage)37 Weak → GC collects at next run38 Soft → GC collects only under memory pressure39 Phantom → GC always collects; used for cleanup40
41♻️ GC TYPES:42 Serial GC → 1 thread | long pause43 Parallel GC → N threads | shorter pause | Java 8 default44 CMS → concurrent | no compaction45 G1 GC → concurrent + compact | Java 9+ default46
47⚠️ KEY INTERVIEW POINTS:48 • JVM manages all memory — you do NOT manually free memory in Java49 • System.gc() = request, NOT command50 • Minor GC = Young Gen (fast, frequent)51 • Major GC = Old Gen (slow, infrequent)52 • Stop-the-World = app threads pause during GC53 • PermGen (before Java 8) → MetaSpace (Java 8+)54 • String literals → Pool (reused) | new String() → Heap (new)End of Chapter — Java Memory Management
try-catch-finally, custom exceptions, checked vs unchecked
- Multithreading — thread stacks, shared heap, synchronization, thread safetyStudy Guide generated from: Java Basics to Advanced — Lecture 4: Java Memory Management
Practice & Implement
Apply what you learned in Memory Management
Create a method `createObjects()` that creates local primitives and objects. Demonstrate that changes to a local int don't affect the caller, but changes through an object reference do.
10 999
Mastery check
How well can you recall this?
Finished this lesson?