How Garbage Collector Works in Android?
Last Updated :
09 May, 2021
First of all garbage pickup on the Dalvik Virtual Machine is often much more relaxed than other Java implementations because it does no compacting. this suggests that the address of objects on the heap never change after their creation, making the remainder of the VM implementation quite a bit simpler. So, Garbage Collector is often given the task of cleaning up when some allocation inside the code fails, it might so happen when situations such as these mentioned below arise:
- OutOfMemoryError is close to being triggered
- When the dimensions of the heap hit some pre-defined soft limit, and
- When a Garbage Collection was explicitly requested.
Each of those causes has its own specification indicating whether the Garbage Collection may be a partial one (only free from the active heap), a concurrent one (do most of the thing marking while other threads running) and whether it's a preserving Garbage Collection (to keep the soft references). Garbage Collection is triggered by a soft allocation limit in the day-to-day scenario, only freeing on the active heap, concurrent, and preserving. Whereas on the other end Garbage Collection triggered just before extreme Out of Memory Exception is full & synchronous! The actual Garbage Collection is completed employing a Mark-Sweep algorithm.
Mark-Sweep Algorithm: How it Works?
The mark-and-sweep algorithm was the primary garbage pickup algorithm to be developed that's ready to reclaim cyclic data structures. When using mark-and-sweep, unreferenced objects aren't reclaimed immediately. But, instead of that, the garbage is kept to accumulate until all the memory reserved for that particular application has been exhausted. When a thing like this occurs the execution of the software is suspended and the mark-and-sweep algorithm is called to collect all the trash, after cleaning every unreferenced object and elements, the execution is again back to normal!
The mark-and-sweep algorithm is named a tracing garbage man because it traces out the whole collection of objects that are directly or indirectly accessible by the program. The objects that a program can access directly are those objects which are referenced by local variables on the processor stack also as by any static variables that ask objects. within the context of garbage pickup, these variables are called the roots. An object is indirectly accessible if it's referenced by a field in another (directly or indirectly) accessible object. An accessible object is claimed to be live. Conversely, an object which isn't live is garbage. To explain the mark-and-sweep algorithm, there are two phases, we need to understand both of those first. They are viz:
Phase #1. (a.k.a. Mark Phase): Refers to finding and marking all accessible objects.
Phase #2. (a.k.a. Sweep Phase): During this phase, the rubbish collection algorithm scans through the heap and reclaims all the unmarked objects.
Here's a Short diagram to help you understand the phases perfectly
(a) Depicts the situation before GC initiate
(b) Depicts the effect of the mark phase of the algorithm
(c) Depicts all the objects left once the sweep phase has completed

A very important note: Only the objects which are 'live' happen to remain in the memory and the other marked fields are set to the 'false' flag again.
While learning about the Garbage Collector it is also worth mentioning the Versions of GC in the Android Operating System:
So, there have been four “versions” of GC within the Android OS.
- Dalvik GC: the primary GC implementation. this was a rigid implementation and could also be thought of as a 'stop the world' type of implementation. It stops all the threads within the VM and does its work.
- ART GC or Generational GC (Lollipop & Marshmallow): the main and largest change. The ART/Dalvik Android Team rewrites the whole GC. It is called so because the objects now have “generations” supported in the time they live.
- ART GC (Nougat): The ART tram revises the whole allocation process in assembly-level code now.
- ART GC (Oreo): The slight improvement in the ART GC v1. This was called the “Concurrent Copying Garbage Collector”
Dalvik? What is it?
Dalvik was the present runtime for Android until KitKat(4.4). But In KitKat, it got merged with the much infamous ART, the fresh new runtime that the Software giant Google was working on and released in parallel with Dalvik with the needs of testing and acquiring feedback from developers partners. In Lollipop it had been replaced entirely for ART. Allocation and collection of objects at this point were slow. this was because the Garbage Collector in the Dalvik is only a thread, i.e. the Dalvik VM pauses all the threads within the VM (all the system threads, the app threads, etc.) and fires the GC to form the collections. therefore the recommendation was to avoid allocations whenever possible.
The Garbage Collector in Dalvik uses the Concurrent Mark and Sweep algorithm mentioned earlier. unreferenced objects aren't reclaimed immediately. Instead, the gathering is delayed until all available memory has been exhausted, meaning that short-lived objects remain in memory tons longer after they become unused. You can learn more about ART here.
Ending Words
So, as you'll see there are tons of changes made to the Collector throughout the different Android versions. The introduction of ART and its new design allow the ART/Dalvik Team to provide improvements, and was, for sure, an excellent change made to the platform itself. The Garbage Collector has evolved to a more growth, mature and robust GC than the one in Dalvik, allowing a way more powerful and efficient allocation and a more fine-grained collection. It also gets improved the way it locks, locking only the threads that need collecting and not the whole VM.
Similar Reads
Z Garbage Collector in Java
Today, it's common for applications to respond to thousands or even millions of users concurrently. Such applications need immeasurable amounts of memory. However, managing all that memory may easily impact application performance. To overcome this issue java 11 includes a lot of improvements and ch
6 min read
OOPs Concepts in Android
Object-oriented programming (OOP) is a programming paradigm that is based on the concept of "objects", which can contain data and code that manipulates that data. In Android, Java is the primary programming language used for developing Android apps. Java is an object-oriented language and it provide
8 min read
How to Read a File in Android?
In android development, data are presents in a form of files, shared preferences, and databases. We have data in different format according to task our app need to do. In the case of a video player or music player app, we have data store in files and how to read those files in Android we learn in th
2 min read
How RecyclerView Works Internally in Android?
RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible the construction of any lists with XML layouts as an item that can be cu
5 min read
How to Use Memory Heap Dumps Data in Android?
When we design an Android application, the most prevalent concern among developers is the program's memory utilization. This is because, Â the majority of people use low-memory devices, if your program uses a lot of memory, you can lose users. The developers are attempting to locate each and every me
6 min read
How Room Works Internally in Android?
Room autogenerates implementations of your @Database and @Dao annotated classes the first time you compile your code after creating a Room Database. The implementation of UserDatabase and UserDao in the preceding example is generated automatically by the Room annotation processor. The autogenerated
5 min read
Introduction to Fragments | Android
Fragment is a piece of an activity that enables a more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different
5 min read
Trace Based collection
Trace-based collection in compiler design is a novel approach to data structure management. It allows programmers to define and use efficient data structures on the fly, instead of being restricted to predefined types like arrays or linked lists. Mark and Sweep Algorithm:Mark and sweep is a garbage
8 min read
Java Collection retainAll() Method
In Java, the retainAll() method of Java Collection retains or keeps only those elements present inside the collection which is given as an argument to the function. Syntax for retainAll() method: boolean retainAll(Collection<?> c);Parameters: c is the collection containing elements retained or
3 min read
Collecting a Stream to an Immutable Collection in Java
Streams and Collectors were introduced in Java 8 introduced the concept of Streams. A Stream is a sequence, a sequence of objects. We generate Streams from input sources like Arrays, Lists, etc., and support aggregation operations like filter, map, limit, reduce, etc. We use Streams to pipeline data
6 min read