Skip to main content

How Garbage Collection Works

The Garbage Collector operates under a simple premise: if an object can no longer be reached by the running application, it is "garbage" and its memory can be reclaimed.


The Mark and Sweep Algorithm

While there are many different GC algorithms in modern JVMs (like G1GC, ZGC, Parallel GC), they all fundamentally rely on a process known as Mark and Sweep.

The process happens in two main phases:

Phase 1: Marking

The Garbage Collector scans the memory starting from the GC Roots (active local variables, static variables, active threads).

  • It traces every single reference pointer from these roots.
  • Any object it can reach is marked as "alive".
  • Any object it cannot reach is considered "unreachable" (garbage).

Phase 2: Sweeping

Once all reachable objects have been marked, the GC sweeps through the heap memory.

  • It deletes all the unmarked (unreachable) objects, freeing up the memory for future use.

(A third phase, Compaction, often occurs afterward, where the GC shifts the surviving objects closer together to eliminate memory fragmentation).


How to make an Object eligible for GC?

An object becomes eligible for Garbage Collection exactly when there are no more active references pointing to it.

As a developer, there are three common ways an object loses all its references:

1. Nullifying a Reference

If you explicitly set a reference variable to null, the object it was pointing to is left stranded in the heap.

public class LabGC1 {

public static void main(String[] args) {
// 1. Create a Student object. 's1' points to it.
Student s1 = new Student("Alice");

// 2. Nullify the reference.
// The Student("Alice") object is now unreachable and eligible for GC!
s1 = null;
}
}

2. Reassigning a Reference

If you point an existing reference variable to a completely new object, the original object loses that reference.

public class LabGC2 {

public static void main(String[] args) {
// 1. 's1' points to "Alice"
Student s1 = new Student("Alice");

// 2. 's2' points to "Bob"
Student s2 = new Student("Bob");

// 3. Reassign s1 to point to what s2 is pointing to ("Bob")
s1 = s2;

// The original Student("Alice") object now has zero references!
// It is eligible for Garbage Collection.
}
}

3. Anonymous Objects

If you create an object without assigning it to a reference variable, it is immediately eligible for garbage collection as soon as the line of code finishes executing.

public class LabGC3 {

public static void main(String[] args) {
// Calling a method on a brand new object without saving it to a variable
new Student("Charlie").printDetails();

// The Student("Charlie") object is now instantly eligible for GC!
}
}