Wednesday, March 11, 2009

How does a Garbage collector act on a circular reference?

This post walks through the Garbage collector's (here after called GC) action in response to circular references in memory.
In order to understand the working of the GC itself, you need to look in to this link - GC in MSDN

If you have a fair enough understanding of the above link, then you can start reading the below...

Say you have two objects in Generation 0; named A and B. One of the field's in A refers to the object B and one of the field's in B refers to object A. If you were to put in simple terms they reference vice versa and hence introduce a "circular reference". The GC when called for action would go and inspect the thread stack for the roots pointing to A and B individually in a regular scenario. But in the case of circular reference, the GC will walk through the thread stack to determine if there is a root for either one of the objects A or B. If at least one of them has a reference then both the objects survive and are pushed to generation 1, If not both of them will be garbage collected.

1 comment:

@VELU said...

Great topic !!

Stumbled upon a similar question on stackoverflow