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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With