Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does garbage collection collect self-referential objects?

If an object is not referenced by any other, then it is subject to be collected by the .NET CLR garbage collector.

However, if objA references objB, objB references objC, and objC references back to objA, how does the garbage collector figure out that they (as a whole) can be collected?

like image 984
athos Avatar asked Dec 13 '11 12:12

athos


2 Answers

The CLR uses a technique known as mark-and-sweep.

As part of this technique, every object can be thought of as initially marked for collection. Then, the CLR goes through each accessible object, starting with your globals (static fields, etc.) as the roots, and clears the mark on each walkable object. It then sweeps the remaining marked objects.

Keep in mind that this "marking" is conceptual; in reality, the objects are most likely added to a collection-set.

In the case of looping self-referenced objects, no reference to the objects will be found from the application, and so the algorithm will never reach those objects to "unmark" them.

like image 192
David Pfeffer Avatar answered Oct 04 '22 17:10

David Pfeffer


GC has a list of all created objects. During garbarge process it starts from global roots (like static fields) and walk through each referenced object. Each object from the list of all which has not been hit can be destroyed.

If there is no way to hit objA, objB or objC, all these objects will be collected

like image 36
Novakov Avatar answered Oct 04 '22 15:10

Novakov