Course Content
Core Java
About Lesson

The garbage collector in Java in regular interval scans the heap memory to find the unreferenced objects i.e. find the objects that are not in use.

https://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html

Process of Garbage Collection

  1. Marking: It is the first step where GC (Garbage Collector) mark all the objects that are still in use i.e. still being referenced by the program. GC starts with a set of root objects and traverse through all the objects that are reachable from the roots. Objects that are not reachable are eligible for garbage collection
  2. Sweeping: After Marking, GC sweeps Java heap to identify and reclaim the memory allocated to the objects are not referenced. Their memories are deallocated, reclaimed and added back to free memory pool.
  3. Compacting (Optional): In some GC algorithms, after sweeping phase, memory that us used by live objects are rearranged to minimize fragmentation. This phase is called Compaction Phase. Active objects are moved closer together creating larger contiguous blocks of free memory.

Scroll to Top