Java Garbage Collection Basics Interview Questions and Answers | JVM GC | Production Scenarios
Master Java Garbage Collection with real interview questions, JVM memory architecture, object lifecycle, GC algorithms, production scenarios, diagrams, and best practices.
Introduction
Garbage Collection (GC) is one of the most important topics in Java interviews. Every Java developer uses objects every day, but few understand how the JVM automatically manages memory behind the scenes.
In enterprise applications like Spring Boot Microservices, thousands or even millions of objects are created every second. Without Garbage Collection, developers would have to manually free memory, leading to memory leaks, crashes, and complex code.
Java's Garbage Collector automatically identifies objects that are no longer needed and reclaims their memory.
Understanding Garbage Collection is essential for:
- Java Developers
- Spring Boot Developers
- JVM Engineers
- Performance Engineers
- Solution Architects
Senior Java interviews almost always include Garbage Collection questions.
Learning Objectives
After completing this article, you'll understand:
- What Garbage Collection is
- Why Java uses Garbage Collection
- JVM Memory Architecture
- Heap vs Stack
- Object Lifecycle
- Reachability Analysis
- GC Roots
- Young Generation
- Old Generation
- Minor GC
- Major GC
- Full GC
- Stop-The-World Events
- Object Promotion
- Memory Leaks
- Real-world Production Scenarios
What is Garbage Collection?
Garbage Collection (GC) is the automatic process of identifying and removing objects that are no longer reachable by the application.
Instead of manually freeing memory, the JVM performs this task automatically.
Example:
public void demo() {
Employee emp = new Employee();
emp = null;
}
After emp becomes unreachable, the object becomes eligible for Garbage Collection.
Important:
Eligible for Garbage Collection does not mean it is immediately removed.
The JVM decides when to reclaim the memory.
Why Do We Need Garbage Collection?
Without Garbage Collection:
- Memory would continuously grow.
- Applications would eventually crash with
OutOfMemoryError. - Developers would manually manage memory.
- Memory leaks would become much more common.
Benefits of Garbage Collection:
- Automatic memory management
- Reduced programming errors
- Improved application stability
- Better developer productivity
JVM Memory Architecture
flowchart TD
Application --> JVM
JVM --> Heap
JVM --> Stack
JVM --> Metaspace
JVM --> NativeMemory["Native Memory"]
Heap --> YoungGeneration["Young Generation"]
Heap --> OldGeneration["Old Generation"]
JVM Memory Areas
| Memory Area | Stores |
|---|---|
| Heap | Objects |
| Stack | Local variables, method calls |
| Metaspace | Class metadata |
| PC Register | Current instruction |
| Native Memory | JNI and native libraries |
Heap Structure
flowchart LR
Heap --> YoungGeneration["Young Generation"]
YoungGeneration["Young Generation"] --> EdenSpace["Eden Space"]
YoungGeneration["Young Generation"] --> SurvivorS0["Survivor S0"]
YoungGeneration["Young Generation"] --> SurvivorS1["Survivor S1"]
Heap --> OldGeneration["Old Generation"]
Object Lifecycle
flowchart TD
NewObject["new Object()"] --> EdenSpaceReferencedUnreachable["Eden Space --> Referenced --> Unreachable --> Marked --> Swept --> Memory Reclaimed"]
How Garbage Collection Works
The JVM continuously checks whether objects are still reachable.
If an object cannot be reached from any GC Root, it becomes eligible for collection.
The process typically involves:
- Mark
- Sweep
- Compact (collector dependent)
Reachability Analysis
Modern JVMs use Reachability Analysis instead of simple reference counting.
Objects are traced from GC Roots.
If an object cannot be reached, it is considered garbage.
flowchart TD
GcRoot["GC Root"] --> ObjectA["Object A"]
ObjectA["Object A"] --> ObjectB["Object B"]
ObjectB["Object B"] --> ObjectC["Object C"]
ObjectX["Object X"] --> ObjectY["Object Y"]
Objects A, B, and C are reachable.
Objects X and Y are unreachable and eligible for GC.
What Are GC Roots?
GC Roots are starting points for reachability analysis.
Examples include:
- Local variables on thread stacks
- Active threads
- Static variables
- JNI references
- System class references
If an object is reachable from any GC Root, it will not be collected.
Object Generations
Java assumes that most objects have short lifetimes.
Objects are categorized into generations.
| Generation | Purpose |
|---|---|
| Young Generation | Newly created objects |
| Old Generation | Long-lived objects |
Young Generation
The Young Generation consists of:
- Eden Space
- Survivor Space 0
- Survivor Space 1
New objects are created in Eden.
After surviving several Minor GCs, they are promoted to the Old Generation.
Object Promotion
flowchart LR
Eden --> SurvivorS0SurvivorS1["Survivor S0 --> Survivor S1 --> Old Generation"]
Objects that survive multiple Minor GCs move to the Old Generation.
Minor GC
Minor GC cleans the Young Generation.
Characteristics:
- Fast
- Frequent
- Low pause time
Major GC
Major GC primarily cleans the Old Generation.
Characteristics:
- Slower
- Less frequent
- Higher pause time
Full GC
Full GC cleans the entire heap.
It includes:
- Young Generation
- Old Generation
- Sometimes Metaspace cleanup
Full GC usually has the highest pause time.
Stop-The-World (STW)
During certain GC phases, the JVM pauses all application threads.
This is called a Stop-The-World (STW) event.
flowchart LR
ApplicationRunning["Application Running"] --> StoptheworldGarbageCollectionApplication["Stop-The-World --> Garbage Collection --> Application Resumes"]
Modern collectors aim to minimize STW pause times.
Frequently Asked Interview Questions
Question 1
What is Garbage Collection?
Answer
Garbage Collection is the JVM process that automatically identifies and removes objects that are no longer reachable, reclaiming heap memory without requiring manual memory management.
Question 2
Why is Garbage Collection required?
Answer
Garbage Collection prevents:
- Memory leaks caused by forgotten deallocation
- Excessive memory consumption
- Application crashes due to exhausted heap space
It also simplifies application development by eliminating manual memory management.
Question 3
Does Java completely eliminate memory leaks?
Answer
No.
Java prevents many memory management errors, but memory leaks are still possible.
Example:
Map<String, Employee> cache = new HashMap<>();
cache.put("1", new Employee());
If entries are never removed, the objects remain reachable and cannot be garbage collected.
Question 4
When does an object become eligible for Garbage Collection?
Answer
An object becomes eligible when it is no longer reachable from any GC Root.
Example:
Employee employee = new Employee();
employee = null;
The object is now eligible for Garbage Collection.
Question 5
Does calling System.gc() immediately trigger Garbage Collection?
Answer
No.
System.gc() is only a request to the JVM.
The JVM may:
- Perform GC
- Ignore the request
- Delay the operation
Never rely on System.gc() for application correctness.
Question 6
What is Reachability Analysis?
Answer
Reachability Analysis starts from GC Roots and traverses object references.
Objects that cannot be reached are considered garbage.
This algorithm replaced simple reference counting because it correctly handles cyclic references.
Question 7
What are GC Roots?
Answer
GC Roots include:
- Local variables
- Active thread stacks
- Static variables
- JNI references
- System classes
Objects reachable from GC Roots remain alive.
Question 8
What is the difference between Heap and Stack?
| Heap | Stack |
|---|---|
| Stores objects | Stores local variables |
| Shared among threads | Thread-specific |
| Managed by GC | Automatically released when methods return |
| Larger memory area | Smaller memory area |
Question 9
What is the Young Generation?
Answer
The Young Generation stores newly created objects.
It consists of:
- Eden
- Survivor Space 0
- Survivor Space 1
Most objects die young, making Minor GC efficient.
Question 10
What is the Old Generation?
Answer
Objects that survive multiple Minor GCs are promoted to the Old Generation.
These are generally long-lived objects such as caches, singleton services, or application-wide data structures.
Question 11
What is Minor GC?
Answer
Minor GC cleans only the Young Generation.
Characteristics:
- Fast
- Frequent
- Small pause times
Question 12
What is Major GC?
Answer
Major GC focuses on reclaiming memory from the Old Generation.
It usually takes longer than Minor GC because it processes long-lived objects.
Question 13
What is Full GC?
Answer
Full GC processes the entire heap.
It typically includes:
- Young Generation
- Old Generation
Full GC has the highest impact on application latency.
Question 14
What is Stop-The-World?
Answer
Stop-The-World (STW) is a JVM pause during which all application threads are suspended while the Garbage Collector performs specific operations.
Modern collectors aim to minimize STW pauses.
Question 15
What is object promotion?
Answer
Objects that survive several Minor GCs are moved from the Young Generation to the Old Generation.
This process is called promotion.
Question 16
What causes frequent Full GC?
Answer
Common reasons include:
- Small heap size
- Memory leaks
- Excessive object creation
- Large caches
- Poor JVM tuning
Question 17
What is an OutOfMemoryError?
Answer
An OutOfMemoryError occurs when the JVM cannot allocate additional memory and Garbage Collection cannot reclaim enough space.
Common causes include:
- Heap exhaustion
- Metaspace exhaustion
- Native memory exhaustion
Question 18
Can cyclic references cause memory leaks?
Answer
No.
Unlike reference-counting systems, Java uses Reachability Analysis.
If a group of objects references each other but none are reachable from a GC Root, the entire cycle is eligible for Garbage Collection.
Question 19
Why do most objects die in the Young Generation?
Answer
Most objects are temporary.
Examples:
- Request DTOs
- REST responses
- Local collections
- String builders
The JVM is optimized for this behavior, making Minor GC efficient.
Question 20
What are common production causes of memory leaks?
Answer
Examples include:
- Growing caches
- Unclosed resources
- Static collections
- ThreadLocal misuse
- Event listener leaks
- Large in-memory collections
These objects remain reachable and therefore cannot be reclaimed.
Production Scenario
Problem
A Spring Boot service becomes slower over time.
Monitoring shows:
- Heap usage continuously increases.
- Full GC occurs every few minutes.
- CPU usage spikes during GC.
Root Cause
A static cache stores user sessions indefinitely:
private static final Map<String, UserSession> CACHE = new HashMap<>();
Expired sessions are never removed, so they remain reachable from a static GC Root.
Solution
- Implement cache eviction.
- Use bounded caches (e.g., Caffeine).
- Monitor heap usage.
- Analyze heap dumps with Eclipse MAT or Java Flight Recorder.
Best Practices
- Minimize unnecessary object creation.
- Reuse expensive objects when appropriate.
- Use bounded caches.
- Close resources properly.
- Monitor heap utilization in production.
- Choose an appropriate Garbage Collector for your workload.
- Regularly analyze GC logs for long-running applications.
Common Mistakes
❌ Assuming System.gc() forces Garbage Collection.
❌ Believing Java completely eliminates memory leaks.
❌ Ignoring Full GC warnings.
❌ Keeping large static collections indefinitely.
❌ Confusing Heap memory with Stack memory.
❌ Assuming eligible objects are immediately collected.
Interview Tips
Senior interviewers frequently ask:
- Explain the complete object lifecycle.
- How does Reachability Analysis work?
- Why did Java move away from reference counting?
- What is the difference between Minor, Major, and Full GC?
- What are Stop-The-World events?
- How are memory leaks still possible in Java?
- How would you investigate a production Full GC issue?
A strong answer combines JVM theory with practical production troubleshooting.
Summary
In this article, we covered:
- Garbage Collection fundamentals
- JVM memory architecture
- Heap and Stack
- Object lifecycle
- Reachability Analysis
- GC Roots
- Young and Old Generations
- Minor, Major, and Full GC
- Stop-The-World events
- Memory leaks
- Production scenarios
- Frequently asked interview questions
- Best practices
- Common mistakes
In the next article, we'll explore Serial GC and Parallel GC, including their internal working, JVM options, throughput optimization, stop-the-world behavior, and production use cases.