Friday, July 3, 2015

Garbage collection and Finalization in .NET



Garbage Collection and Finalization

When an object is instantiated, it goes Managed heap. There are also 2 special queues where the objects might go depending on certain conditions -

Finalization Queue - When an object is instantiated, if it has finalize method implemented ( as Destructor - ~ClassName), an entry is done in the Finalization queue as
well, in addition to the Managed heap.

F-Reachable Queue

During GC scan, when the garbage is found (no application roots present after traversing - Check second diagram below) , it checks its presence in Finalization queue.
If found in Finalization queue, it moves them to F-Reachable queue.
If not found in Finalization queue, it is collected.


If an object makes its way to the F-Reachable queue, its NOT garbage. Another special thread runs which clears the F-Reachable queue.

Once it clears the F-Reachable queue, the next time GC runs. It would remove those object from managed heap. (as no entry of them is present in Finalization queue AND F-Reachable queue).

======Optimization in GC (Generation based garbage collection)=======

Assumption - NEWER OBJECTS HAVE LESSER LIFELINE (OLDER OBJECTS HAVE LONGER LIFELINE)

1) First time, objects are added to the managed heap, its in GEN 0.
2) GC runs using the above complex steps and collects some garbage objects. Those objects which survived (not garbage) are moved to GEN 1. Some new objects might be added during this time to the managed heap. It will be in GEN 0.
3)Next GC run happens - surviving objects (not garbage) GEN numbers are increased. GEN 1 are in GEN 2. and earlier GEN 0 are now in GEN 1. In the meantime, some new objects might be added to the managed heap. It will be in GEN 0. (Will look like third image below).
4)During collection, GC only scans GEN 0 instead of entire heap (based on the above assumption). Hence the optimization.


Some diagrams for illustration –

Need of Garbage collection here





Not Reachable by Application Roots, Found Garbage (Grey colored objects) –




Depiction of Generations in objects

No comments:

Post a Comment