DEV Community

Aswin Arya
Aswin Arya

Posted on

How Does Garbage Collector Work Internally in Java?

The Garbage Collector (GC) in Java is an automatic memory management system that removes unused objects from heap memory, helping applications run efficiently without manual memory cleanup.

👉 Its main goal is to free memory occupied by objects that are no longer reachable.


🔹 Step-by-Step Internal Working of Garbage Collector

1. Object Creation in Heap Memory

Whenever objects are created using the new keyword, they are stored in Heap Memory.

Student s = new Student();
Enter fullscreen mode Exit fullscreen mode

2. Reachability Analysis (Key Concept)

GC checks whether objects are still reachable from GC Roots.

GC Roots include:

  • Local variables in stack
  • Active threads
  • Static variables
  • JNI references

👉 If an object cannot be reached from GC Roots, it becomes eligible for garbage collection.


3. Mark Phase

GC scans memory and marks all reachable (alive) objects.

  • Reachable → Marked alive
  • Unreachable → Marked for removal

4. Sweep Phase

All unmarked objects are removed from memory, freeing heap space.


5. Compact Phase (Memory Optimization)

Remaining objects are rearranged to:

  • Remove memory gaps
  • Reduce fragmentation
  • Improve allocation performance

🔹 Generational Garbage Collection

Java divides heap memory into generations because most objects die young.

Young Generation

  • Newly created objects
  • Minor GC happens frequently

Old (Tenured) Generation

  • Long-living objects
  • Major GC occurs less often

Metaspace

  • Stores class metadata

🔹 Types of Garbage Collection

  • Minor GC → Cleans Young Generation
  • Major GC → Cleans Old Generation
  • Full GC → Cleans entire heap

🔹 Algorithms Used by GC

  • Mark and Sweep
  • Mark and Compact
  • Copying Algorithm
  • Generational Collection

🔹 Advantages

  • Automatic memory management
  • Prevents memory leaks (mostly)
  • Improves developer productivity

✅ Promotional Content

To deeply understand JVM internals, Garbage Collection, memory optimization, and real-time Java performance tuning through practical implementation, join the Best Java Real Time Projects Online Training in Ameerpet.

Top comments (0)