Connect with us


Android Garbage Collection in a Nutshell

Have you ever wondered how Garbage Collection works under the hood in Android?

Have you ever wondered how Garbage Collection works under the hood in Android?

The term “under the hood” basically, boils down to these 4 simple questions:

  1. What is GC?
  2. How it works internally?
  3. What happens when it fails?
  4. Who is eligible for GC?

1. What is GC?

GC is a mechanism of collecting unused objects and freeing up (recycling ♺) the memory space for further usage.

2. How it works internally?

Till now, there were 5 versions of GC, in the Android OS, namely:

  1. Dalvik GC (Until KitKat): “Stop the World GC”
  2. ART GC (Lollipop and Marshmallow): Generational GC
  3. ART GC (Nougat): ART/Dalvik Android Team rewrites the entire allocation process in assembly code.
  4. ART GC (Oreo): “Concurrent Copying GC”
  5. ART GC (Android 10 onwards): Re-introduced “Generational GC” as an extension of powerful “Concurrent Copying GC”!

Dalvik “Stop the World GC”

Until KitKat

This GC runs on : “Concurrent Mark-and-Sweep” (CMS) algorithm

Let’s understand this algorithm:

Step 1: Find Roots:

  • The GC pauses all the threads in the system to find the roots (we will talk about the “roots” later in this course. At a very high level, for now, just think of it as a root node in a tree).
  • This phase is not concurrent, so identifying roots takes time, and during this time the application cannot do anything.
  • In this phase, one boolean flag “marked” is set to “false” by default for each and every object.

Step 2: Mark Reachable Objects:

  • The objects which have a direct or indirect reference to the roots are marked as REACHABLE in this phase! (We’ll also talk about Object Reachability at later point of this article. Please, bear with me!