Apr 13 2007

How does the GC handle circular references?

Category: .NetRory Primrose @ 10:35

I am a little curious about how the garbage collector cleans up CLR objects. From what I understand, it will wait until objects are de-referenced and then will go through a couple of generations (as required) to release objects from memory.

The following is a simple scenario of GC:

Object A that has a reference to B that has a reference to C. When A goes out of scope, the GC can collect it. When it removes A, B is has a reference count of 0 and can also be removed and then likewise for C as B is removed.

Side question: does this happen in the same GC cycle or is this over three GC cycles?

Ok, simple enough. But how does the GC handle the following scenario:

Object A has a reference to B which has a reference to C. C has a reference back to B.

When A goes out of scope, is B available for the GC as it is still referenced by C? How does the GC handle these circular references?

Tags:

Comments (3) -

1.
Joseph Cooney Joseph Cooney says:

The GC doesn't (AFAIK) use reference counting as such. It starts with a set of objects that are not going to be collected, which it marks. It then traverses the objects that have been marked, and marks all of the un-marked objects that are directly referenced by marked ones. The is the "mark" part of the "mark and sweep" process which accurately describes how it works.

If A goes out of scope next time the garbage collector runs neither A, B or C will be marked so they will all be eligible for collection. They can hold as many references to each other as they like, but because they're not referenced by anything that has been marked (and thus is going to stay around) it is irrelevant. The GC isn't something that is is sitting in the background looking to clean up individual objects when the reference count reaches zero, it is a process that runs periodically when a heuristic determines when it needs to run. When it does a GC of a particular generation all the objects in that generation will be inspected to see if they are eligible for collection.

2.
Rory Primrose Rory Primrose says:

Thanks Joseph. I was sure that the GC was very smart about how to handle these circular references.

3.
Barfieldmv Barfieldmv says:

A good answer Joseph.

Using circulair references does make destructors a lot harder to program. One of the two objects will be delete first and you wont know wich one.

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading