Skip to content
C

Garbage Collector

The Garbage Collector is the actual component within the JVM responsible for performing garbage collection — scanning the Heap, identifying unused objects, and reclaiming their memory.


1. What is the Garbage Collector?

The Garbage Collector is the actual component within the JVM responsible for performing garbage collection — scanning the Heap, identifying unused objects, and reclaiming their memory.

2. Why is it used?

It's the mechanism that actually carries out the memory-cleanup process described in the previous topic, working automatically in the background as a Java program runs.

3. Real-Life Example

If garbage collection is "the process of cleaning," the Garbage Collector is "the cleaning staff" who actually does the physical work of removing waste from the building.

4. Syntax

java
// The Garbage Collector runs automatically; no direct syntax to control its internal work

5. Example Program

java
public class GarbageCollectorDemo { public static void main(String[] args) { for (int i = 0; i < 3; i++) { String temp = new String("Object " + i); System.out.println(temp + " created"); } // Once this loop ends, these temporary objects become eligible // for cleanup by the Garbage Collector. } }

Output:

Object 0 created
Object 1 created
Object 2 created

6. Key Points to Remember

  • Java offers several types of Garbage Collectors (like G1, Serial, and Parallel Collector), each suited to different application needs.
  • The Garbage Collector runs on its own schedule, decided internally by the JVM, not directly by the programmer.
  • Programmers cannot force immediate garbage collection — System.gc() is only ever a suggestion, not a command.