Hello! In our last lesson, we explored the key memory areas within the JVM, establishing that all Java objects live on the Heap. We saw that when an object is no longer referenced—perhaps because the method that created it has finished and its stack frame has been popped—it becomes eligible for cleanup. This brings us to a crucial question that interviewers love to ask: how does the JVM automatically reclaim this memory?
Today, we'll answer that question by diving into the fundamental process of Garbage Collection (GC). You'll learn about the core algorithm that underpins most of Java's sophisticated memory management systems. Understanding this process is not just an academic exercise; it's a key differentiator in technical interviews, separating developers who simply use the language from those who understand how it truly works under the hood. Our goal is to explain the essential phases of this process: Mark, Sweep, and Compact.
The Problem: Reclaiming Unused Memory
As we discussed, objects are allocated on the Heap, a large, shared memory pool. Without a mechanism to clean up unused objects, the Heap would quickly fill up, leading to an OutOfMemoryError. In languages like C or C++, memory management is manual; the developer is responsible for both allocating and deallocating memory. This approach is powerful but notoriously error-prone, often leading to memory leaks (forgetting to free memory) or dangling pointers (freeing memory that is still in use).
Java's solution is automatic memory management via the Garbage Collector (GC). The GC is a process that runs in the background, identifying and deleting objects that are no longer needed by the application. This automation is a cornerstone of Java's safety and developer productivity. However, it comes with its own set of complexities and performance trade-offs. The most significant is the "stop-the-world" pause, where the application's execution is temporarily halted while the GC does its work. Minimizing these pauses is the primary goal of modern GC algorithms.
The Foundational Algorithm: Mark-Sweep-Compact
While Java has several advanced garbage collectors, most are built upon a classic, three-phase algorithm: Mark, Sweep, and Compact. Let's break down each phase.
1. The Mark Phase: Finding All Live Objects
The first step is to figure out which objects are still in use and which are not. The GC can't just look at an object in isolation; it needs to know if there's a "path" to that object from somewhere in the running application. The starting points of these paths are called GC Roots.
How the Mark-Sweep-Compact Algorithm Works
This article from the GCeasy blog provides an excellent, detailed breakdown of the Mark-Sweep-Compact process. We'll start with the first phase.
Under the heading "The Mark-Sweep-Compact Algorithm in Java: How it Works", please read the subsection titled "1. Mark Phase". Pay close attention to the list of what constitutes GC Roots. This is the crucial starting point for the whole process. Understand how the GC traverses the "reference chain" from these roots to identify all live objects.
To summarize, the Mark phase works like this:
- Identify GC Roots: These are a set of special references that are always considered "live." They include:
- References from the call stack (local variables and parameters of currently executing methods).
- Static variables.
- References from Java Native Interface (JNI) code.
- Traverse the Object Graph: Starting from these roots, the GC follows every reference to other objects, then the references from those objects, and so on. Think of it like exploring a graph.
- Mark as Live: Every object the GC can reach during this traversal is marked as "live." Any object it cannot reach is, by definition, "garbage."
2. The Sweep Phase: Reclaiming Garbage
Once the Mark phase is complete, the JVM knows exactly which objects are live and which are garbage. The next step is straightforward.
How the Mark-Sweep-Compact Algorithm Works
Now, let's look at what happens to the unmarked objects.
Continue in the same article and read the subsection titled "Sweep Phase". This section describes how the memory from unreferenced objects is reclaimed.
The Sweep phase scans the entire heap. For every object, it checks the "mark" that was set in the previous phase.
- If an object is marked (live), its mark is cleared in preparation for the next GC cycle.
- If an object is unmarked (garbage), its memory is reclaimed and added to a list of free memory blocks that can be used for future allocations.
However, this simple approach introduces a significant problem: memory fragmentation. After sweeping, the heap is left with live objects interspersed with free memory blocks, like holes in a slice of Swiss cheese. This can prevent the allocation of a large object, even if the total amount of free memory is sufficient, because no single free block is large enough.
3. The Compact Phase: Defragmenting the Heap
To solve the fragmentation problem, an optional third phase, Compaction, is added.
How the Mark-Sweep-Compact Algorithm Works
Finally, let's see how the GC addresses the problem of fragmentation.
Read the final subsection, "Compact Phase". Focus on the purpose of this phase and understand why it is considered an "expensive" operation.
During the Compact phase, all live objects are moved to one end of the heap. This eliminates the gaps and leaves a single, large, contiguous block of free memory.
- Advantage: New object allocations become extremely fast. The JVM simply needs to maintain a single pointer to the start of the free memory block. To allocate a new object, it "bumps the pointer" forward by the required amount. This is called "bump-the-pointer allocation."
- Disadvantage: Compaction is a costly operation. Not only do all live objects need to be moved, but every single reference to those objects (from the stack, from other heap objects, etc.) must be updated to point to their new memory locations.
Visualizing the Process
Let's look at how this three-phase process transforms the memory layout.

The difference between a heap after a simple Sweep versus one after a Sweep and Compact is critical.

For a dynamic explanation, the following video segment clearly illustrates the entire algorithm.
Top 10 Interview Questions on Garbage Collection | Mark and Sweep Algorithm? Major vs Minor GC
This video from "Code With Ease" provides a concise, interview-oriented explanation of the Mark and Sweep algorithm, including compaction.
Watch the segment explaining the classic GC algorithm from this timestamp. The presenter's visualization of marking, sweeping, and compacting the live objects reinforces the concepts we've just discussed.
An Important Distinction: Minor vs. Major GC
In our last lesson, we briefly mentioned that the Heap is often divided into a Young Generation and an Old Generation. This division is key to optimizing GC performance. Most objects "die young," meaning they become garbage shortly after being created. The JVM leverages this fact by performing frequent, fast cleanups on the Young Generation, a process called a Minor GC.
Objects that survive several Minor GC cycles are considered "long-lived" and are eventually promoted to the Old Generation. A GC event that cleans the Old Generation is called a Major GC (or a Full GC if it cleans the entire heap). Major GCs are less frequent but much slower and more disruptive.
Understanding this distinction is a common interview requirement.
Top 10 Interview Questions on Garbage Collection | Mark and Sweep Algorithm? Major vs Minor GC
Let's return to the "Code With Ease" video for a clear explanation of this crucial interview topic.
Watch the segment from this timestamp. It clearly breaks down the difference between Minor and Major GC and where each one operates within the heap.
Conclusion
In this lesson, we've demystified the process of automatic memory management in Java. You now have a solid mental model of how the Garbage Collector works at a fundamental level.
Here are the key takeaways for your interview preparation:
- Garbage Collection is Java's mechanism for automatically reclaiming memory from objects that are no longer referenced.
- The foundational algorithm is Mark-Sweep-Compact.
- Mark: Traverses the object graph from GC Roots to identify all live objects.
- Sweep: Reclaims memory from unreferenced objects, but can cause memory fragmentation.
- Compact: Moves live objects together to create a contiguous block of free memory, enabling fast "bump-the-pointer" allocations but incurring a high performance cost.
- GC events are categorized as Minor GC (frequent, fast, in Young Generation) and Major GC (less frequent, slow, in Old Generation).
You have now built a strong foundation by understanding both the JVM's memory layout and the basic mechanism for keeping it clean. However, modern applications demand more sophisticated GC strategies to minimize those disruptive "stop-the-world" pauses.
In our next lesson, we will build upon these concepts to explore how modern garbage collectors like G1 GC and ZGC work, comparing their mechanisms and the trade-offs they make to deliver high throughput and low latency.