JVM, JRE & JDK Chapter
Garbage Collector Interview Questions and Answers
Learn how the JVM's Garbage Collector reclaims unused memory, from Mark-and-Sweep and generational collection to Stop-the-World events and modern low-latency collectors.
Garbage Collector interview questions
Garbage Collector Interview Question 15 Questions
Click on any question to expand the answer.
Interview Answer
Garbage Collection (GC) is the automatic memory management process performed by the JVM to reclaim memory occupied by objects that are no longer in use. It eliminates the need for developers to manually free memory, reducing the chances of memory leaks and program crashes. GC helps Java applications run efficiently by managing heap memory automatically.
Key Points
- GC stands for Garbage Collection.
- It is an automatic memory management mechanism.
- It removes unreachable objects from the heap.
- It helps prevent memory leaks and
OutOfMemoryError. - It improves application reliability and developer productivity.
Interview Tips
- Mention that Garbage Collection manages only heap memory.
- Explain that developers cannot explicitly free memory in Java.
Summary
Garbage Collection automatically reclaims unused heap memory, making Java applications more reliable and easier to develop. It is one of Java's key features for efficient memory management.
Interview Answer
The Garbage Collector periodically scans heap memory to identify objects that are no longer reachable from any active reference. It marks live objects, removes unreachable objects, and reclaims their memory for future allocations. Depending on the collector, it may also compact memory to reduce fragmentation and improve allocation efficiency.
Key Points
- Scans heap memory for unreachable objects.
- Uses reachability analysis instead of reference counting.
- Marks live objects before reclaiming memory.
- Frees memory occupied by unreachable objects.
- May compact heap memory after collection.
- Runs automatically under JVM control.
Interview Tips
- Explain that the JVM decides when to perform Garbage Collection.
- Mention that different Garbage Collectors use different algorithms.
Summary
The Garbage Collector automatically identifies unused objects and reclaims their memory. This process keeps heap memory available without requiring manual memory management.
Interview Answer
An object becomes eligible for Garbage Collection when it is no longer reachable from any live thread or GC root. The JVM performs reachability analysis by starting from GC roots, such as local variables, static variables, and active threads, and follows object references. Objects that cannot be reached through this process are considered eligible for collection.
Key Points
- Unreachable objects are eligible for Garbage Collection.
- The JVM uses reachability analysis.
- GC roots include local variables, static fields, and active threads.
- Reachable objects are never collected.
- Eligibility does not guarantee immediate collection.
Interview Tips
- Explain that Java uses reachability analysis instead of reference counting.
- Mention that an eligible object may remain in memory until the next GC cycle.
Summary
The JVM determines object eligibility using reachability analysis. Objects that are no longer connected to any GC root become candidates for Garbage Collection.
Interview Answer
Java categorizes object references based on their reachability to determine how the Garbage Collector should treat them. Strong references prevent objects from being collected, while soft, weak, and phantom references provide different levels of accessibility before collection. These reference types help balance memory usage, caching, and resource management.
Key Points
| Reference Type | Description |
|---|---|
| Strongly Reachable | Object has a normal reference and cannot be garbage collected. |
| Softly Reachable | Collected only when the JVM needs memory. |
| Weakly Reachable | Collected during the next Garbage Collection cycle. |
| Phantom Reachable | Used for post-cleanup processing after finalization. |
| Reachable | Accessible through at least one valid reference chain. |
| Unreachable | No reference path exists from any GC root. |
Interview Tips
- Remember that strong references have the highest priority.
- Soft and weak references are commonly used in caching implementations.
Summary
Java provides multiple reference types to control object lifetime and memory usage. Understanding these reference categories is important for advanced memory management.
Interview Answer
The Mark-and-Sweep algorithm is one of the fundamental Garbage Collection algorithms used by the JVM. During the Mark phase, the Garbage Collector identifies all reachable objects by traversing references from GC roots. During the Sweep phase, it removes all unmarked objects and reclaims their memory for future allocations.
Key Points
- Consists of two phases: Mark and Sweep.
- The Mark phase identifies reachable objects.
- The Sweep phase removes unreachable objects.
- Uses reachability analysis instead of reference counting.
- Forms the foundation for many modern Garbage Collection algorithms.
Interview Tips
- Explain both phases in the correct order.
- Mention that some modern collectors also perform memory compaction after the Sweep phase.
Summary
The Mark-and-Sweep algorithm identifies live objects and removes unreachable ones. It is a core concept behind Java's automatic memory management and many modern Garbage Collection techniques.
Interview Answer
The Garbage Collection process generally consists of three phases: Mark, Sweep, and Compact. During the Mark phase, the JVM identifies all reachable objects. The Sweep phase removes unreachable objects, and the Compact phase reorganizes the remaining objects to eliminate memory fragmentation and improve allocation efficiency.
Key Points
- Mark – Identifies all reachable (live) objects.
- Sweep – Reclaims memory occupied by unreachable objects.
- Compact – Moves live objects together to remove memory fragmentation.
- Compaction improves future memory allocation speed.
- Not every Garbage Collector performs all three phases in the same way.
Interview Tips
- Remember the sequence: Mark → Sweep → Compact.
- Mention that modern collectors optimize these phases differently.
Summary
The Mark, Sweep, and Compact phases work together to reclaim unused memory and maintain efficient heap organization. They form the foundation of modern Java Garbage Collection.
Interview Answer
Minor GC collects objects from the Young Generation, where most new objects are allocated. Major GC primarily collects objects in the Old Generation, while Full GC performs garbage collection across the entire heap and may also clean Metaspace. Full GC is generally the most expensive and can cause longer application pauses.
Key Points
| GC Type | Memory Area | Characteristics |
|---|---|---|
| Minor GC | Young Generation | Fast and occurs frequently |
| Major GC | Old Generation | Slower and occurs less often |
| Full GC | Entire Heap and often Metaspace | Most expensive collection |
- Most newly created objects are reclaimed during Minor GC.
- Objects that survive multiple Minor GCs are promoted to the Old Generation.
- Full GC usually causes the longest pause times.
Interview Tips
- Clearly distinguish the memory areas handled by each GC type.
- Mention that Minor GC is much more common than Full GC.
Summary
Minor, Major, and Full GC differ in the memory areas they collect and their execution cost. Understanding these differences is important for JVM performance tuning.
Interview Answer
The JVM divides memory into different regions to optimize Garbage Collection. The Young Generation stores newly created objects, the Old Generation stores long-lived objects, and Metaspace stores class metadata. Each area has its own Garbage Collection behavior to improve memory management and application performance.
Key Points
| Memory Area | Stores |
|---|---|
| Young Generation | Newly created objects |
| Old Generation | Long-lived objects |
| Metaspace | Class metadata and runtime information |
- Minor GC primarily collects the Young Generation.
- Major or Full GC collects the Old Generation.
- Metaspace is cleaned when class metadata becomes unused.
- Objects surviving multiple Minor GCs are promoted to the Old Generation.
Interview Tips
- Do not confuse Metaspace with the Heap.
- Remember that Metaspace replaced PermGen starting with Java 8.
Summary
The JVM separates memory into Young Generation, Old Generation, and Metaspace to optimize Garbage Collection. This design improves performance while reducing unnecessary memory overhead.
Interview Answer
Java provides multiple Garbage Collectors designed for different workloads and performance goals. Some focus on maximizing throughput, while others minimize pause times or support very large heaps. Choosing the appropriate collector depends on the application's requirements.
Key Points
| Garbage Collector | Best Use Case |
|---|---|
| Serial GC | Small applications and single-CPU environments |
| Parallel GC | High-throughput batch processing |
| G1 GC | General-purpose server applications with large heaps |
| ZGC | Very large heaps requiring extremely low pause times |
| Shenandoah GC | Low-latency applications with large heap sizes |
- G1 GC is the default collector in modern Java releases.
- ZGC and Shenandoah are designed for low-latency systems.
- Parallel GC prioritizes throughput over pause time.
- Serial GC is suitable for small applications.
Interview Tips
- Know the primary use case for each Garbage Collector.
- Mention that G1 GC is the default collector in current JDK versions.
Summary
Each Java Garbage Collector is optimized for specific workloads. Selecting the right collector helps balance throughput, latency, and memory usage.
Interview Answer
The main difference between Java Garbage Collectors lies in how they balance throughput, pause time, and scalability. Serial GC focuses on simplicity, Parallel GC maximizes throughput, G1 GC balances throughput and latency, while ZGC and Shenandoah are designed to minimize pause times even for very large heaps.
Key Points
| Garbage Collector | Throughput | Pause Time | Typical Use Case |
|---|---|---|---|
| Serial GC | Low | High | Small desktop applications |
| Parallel GC | Very High | Moderate | Batch processing and compute-intensive applications |
| G1 GC | High | Low | General-purpose enterprise applications |
| ZGC | High | Very Low | Large-memory, low-latency applications |
| Shenandoah GC | High | Very Low | Real-time and latency-sensitive systems |
- Parallel GC prioritizes maximum throughput.
- G1 GC balances performance and responsiveness.
- ZGC and Shenandoah provide extremely short pause times.
- The best collector depends on application requirements.
Interview Tips
- Compare the collectors based on throughput, latency, and scalability.
- Remember that no single Garbage Collector is ideal for every application.
Summary
Java offers multiple Garbage Collectors to meet different performance requirements. Understanding their strengths and trade-offs helps developers choose the most suitable collector for their applications.
Interview Answer
A Stop-the-World (STW) event is a period during which the JVM temporarily pauses all application threads so the Garbage Collector can safely perform memory management tasks. These pauses ensure heap consistency while identifying, moving, or reclaiming objects. Modern Garbage Collectors such as G1, ZGC, and Shenandoah are designed to minimize the duration of STW events.
Key Points
- STW pauses all application threads.
- It occurs during certain Garbage Collection phases.
- Ensures safe and consistent memory management.
- Long STW pauses can reduce application responsiveness.
- Modern Garbage Collectors significantly reduce pause times.
Interview Tips
- Mention that STW cannot be completely eliminated but can be minimized.
- Explain that low-latency collectors reduce the impact of STW events.
Summary
Stop-the-World events are necessary for safe Garbage Collection but temporarily pause application execution. Modern JVM collectors reduce these pauses to improve application responsiveness.
Interview Answer
The JVM provides diagnostic options and monitoring tools to analyze Garbage Collection behavior and identify performance issues. GC logs show collection activity, while tools such as JVisualVM, Java Flight Recorder (JFR), and Java Mission Control (JMC) provide detailed insights into heap usage, pause times, and memory allocation. Developers use this information to tune JVM settings and improve performance.
Key Points
- Enable GC logging to monitor collection activity.
- Analyze heap usage and GC frequency.
- Use JVisualVM for memory and CPU monitoring.
- Use JFR to record JVM runtime events.
- Use JMC to analyze JFR recordings.
- Tune the JVM only after analyzing collected data.
Syntax
java -Xlog:gc MyApplication
java -Xlog:gc* MyApplicationInterview Tips
- Mention both GC logs and monitoring tools.
- Explain that performance tuning should be based on measurements rather than assumptions.
Summary
GC logs and JVM profiling tools help developers understand Garbage Collection behavior. Proper analysis enables effective JVM tuning and improved application performance.
Interview Answer
A memory leak in Java occurs when objects that are no longer needed remain reachable through active references, preventing the Garbage Collector from reclaiming their memory. Although Java provides automatic memory management, poor coding practices can still cause memory leaks. These issues can be detected using heap analysis and profiling tools and prevented by releasing unnecessary references.
Key Points
- Memory leaks occur because objects remain reachable.
- Garbage Collection cannot reclaim reachable objects.
- Common causes include static collections, caches, listeners, and unclosed resources.
- Heap dumps and profilers help identify memory leaks.
- Remove unused references and close resources properly.
Interview Tips
- Explain that Garbage Collection cannot fix logical memory leaks.
- Mention heap dump analysis as a common troubleshooting technique.
Summary
Automatic Garbage Collection does not eliminate all memory management problems. Developers must avoid unnecessary references and use profiling tools to detect and prevent memory leaks.
Interview Answer
The finalize() method was originally designed to allow an object to perform cleanup before being reclaimed by the Garbage Collector. However, it was deprecated because its execution is unpredictable, can delay Garbage Collection, and may introduce performance and security issues. Modern Java recommends using try-with-resources and the AutoCloseable interface for deterministic resource management.
Key Points
finalize()was intended for cleanup before object destruction.- Its execution timing is not guaranteed.
- It was deprecated because of reliability and performance issues.
- Use try-with-resources for automatic resource cleanup.
- Implement
AutoCloseablefor custom resources.
Example
Using try-with-resources:
try (FileInputStream fis = new FileInputStream("data.txt")) {
// Use the resource
}Interview Tips
- Mention that
finalize()is deprecated and should not be used in new code. - Recommend try-with-resources as the preferred alternative.
Summary
The finalize() method is no longer recommended because it provides unreliable cleanup behavior. Modern Java applications should use try-with-resources and AutoCloseable for safe and predictable resource management.
Interview Answer
When an object is created, the JVM allocates memory for it in the Young Generation of the heap. As the application executes, reachable objects remain in memory, while unreachable objects become eligible for Garbage Collection. Objects that survive multiple Minor GCs are promoted to the Old Generation, and eventually unreachable objects are reclaimed, making memory available for future allocations.
Key Points
- Objects are initially allocated in the Young Generation.
- Reachability analysis determines whether an object is still in use.
- Minor GC collects short-lived objects.
- Long-lived objects are promoted to the Old Generation.
- Unreachable objects are reclaimed automatically.
- Automatic memory management improves performance and reduces developer effort.
Interview Tips
- Explain the complete object lifecycle in the correct order.
- Mention both object promotion and automatic reclamation.
Summary
The JVM manages objects throughout their lifecycle, from creation to reclamation, using automatic Garbage Collection. This process improves memory utilization, application stability, and overall performance.