Generations in GC

There are three kinds of generation in garbage collection known as Generation 0, Generation 1, and Generation 2. In this section, we will look at the concept of generations and how it affects the performance of the garbage collector.

Let's suppose we run an application that creates three objects named Object1, Object2, and Object3. These objects will allocate the memory in Generation 0:

Now, when the garbage collector runs (this is an automatic process, unless you explicitly call the garbage collector from the code), it checks for the objects that are not needed by the application and have no reference in the program. It will simply remove those objects. For example, if the scope of Object1 is not referenced anywhere, the memory for this object will be reclaimed. However, the other two objects, Object1 and Object2, are still referenced in the program, and will be moved to Generation 1.

Now, let's suppose two more objects, called Object4 and Object5, are created. We will store them in the Generation 0 slot, as shown in the following diagram:

When garbage collection runs the second time, it will find two objects called Object4 and Object5 in Generation 0 and two objects called Object2 and Object3 in Generation 1. Garbage collector will first check the reference of those objects in Generation 0 and, if they are not used by the application, they will be removed. The same goes for the Generation 1 objects. For example, if Object3 is still referenced, it will be moved to Generation 2 and Object2 will be removed from Generation 1, as shown in the following diagram:

This concept of generations actually optimizes the performance of GC, and the objects stored in Generation 2 are more likely to be stored for a longer period. GC performs fewer visits and gains time instead of checking each object again and again. The same goes for Generation 1, which is also less likely to reclaim the space than Generation 0.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.19.63.106