Garbage Collection in Java

Samyak Shreyash
3 min readMay 30, 2021

--

Garbage Collection(GC) is the process of de-allocation of objects in Java. In simpler terms, GC reclaims the heap space previously allocated to objects no longer needed.

Garbage Collection is generally overlooked by Java programmers, due to the over simplification of the entire process by JVM itself. And that makes it more important for us to understand it better.

The two main components for GC to work are a generational object memory system, located in the Heap memory and a sophisticated GC algorithm. A generational memory system divides the heap into a few carefully sized partitions called generations. The efficiency is based on the observation that most of the objects are short-lived.

The heap space is divided into separate parts. At a broad level, it can be classified as Young Generation and Old Generation. The young generation includes the new object space(Eden) and two survivor spaces(S0 and S1).

JVM allocates new objects in the Eden spaces. The young generation uses a fast copying garbage collector which employs two survivor spaces in the Eden. When Eden is filled with objects, minor GC is performed and all the survivor objects are moved to the 1st survivor space. Minor GC also checks the survivor objects and move them to the other survivor space, thus keep one of the survivor space always empty. Objects surviving after many cycles of GC, are moved to the Old Generation. Old generation memory contains the objects that are long-lived and survived after many rounds of Minor GC. When it’s full, it undergoes Major GC.

Mark and Sweep Model

While, generations decide how memories are classified for GC, GC itself is carried out by the Mark and Sweep model. This consists of two phase, mark and sweep phase. During the mark phase, all objects reachable from Java threads, native handles and other root sources are marked alive. While during the sweep phase, the heap is traversed to find gaps between the live objects. These gaps are recorded in free list and are made available for new object allocation.

Concurrent Mark and Sweep

Compaction

At the end, objects that are allocated next to each other will not be de-allocated at the same time, leading to fragmentation. Free spaces that are smaller then the minimum thread local area(TLA) size can not be used again for allocation of objects. Compaction moves object closer together and further down the heap, thus creating larger free ares near the top of the heap.

Compaction is performed at the beginning of or during the sweep phase while all Java threads are paused.

References:

  1. Managing Memory and Garbage Collection
  2. Tuning the Memory Management System

--

--

No responses yet