Garbage Collector and Circular Link

Consider these two classes:

public class A { B b; public A(B b) { this.b = b; } } public class B { A a; public B() { this.a = new A(this); } } 

If I have the classes created above, will objects of such classes be collected by the garbage collector (GC)?

Suppose I do this:

 void f() { B b = new B(); } 

In this method, I create an instance of B called B , and when the method returns, B goes out of scope and the GC should be able to collect it, but if it should collect it would have to first collect a , which is a member of B , and collect a , he needs to first collect B , which is a member of a . It becomes circular. So my question is: is such a circular reference a prevent collection of GC objects?

  • If so, how can we avoid this problem? How can we make sure we don’t have a circular link in our class? Is there any tool (or compiler option) that helps us detect a circular reference?
  • If not, where and why do we use the WeakReference class? What is his purpose?
+44
garbage-collection c # circular-reference
Jan 12 2018-12-12T00:
source share
4 answers

The .Net garbage collector can absolutely handle circular references. A high level of how the garbage collector works, ...

  • Start with locals, statics, and GC pinned objects. None of them can be collected.
  • Mark each object that can be achieved by moving the children of these objects.
  • Collect each object that is not marked.

This allows you to collect circular links just fine. As long as none of them can be reached from an object that, as you know, is unimaginable, then a circular link is essentially irrelevant.

Note. I understand that I have missed a lot of interesting details so that this answer is simple and straightforward.

+70
Jan 12 '12 at 18:48
source share

No, that won't be a problem, because the GC can handle Circular References.

MSDN says

If a group of objects contains references to each other, but none of these objects directly or indirectly refer to the stack or shared variables, then the collection will automatically restore memory to garbage.

+22
Jan 12 '12 at 18:48
source share

Several answers have already explained that circular links are not a problem.

As for weak links, the reason for using them is caching.

When the GC walks through object dependency trees, it ignores weak references. In other words, if the only reference to the object is weak, it will be garbage collection, but if there were no garbage collection between creating the link and your attempt to use it, you can still access the object.

+5
Jan 12 '12 at 19:00
source share

No, the circular reference will not affect the garbage collector, and it will be fully capable of collecting instance B.

The garbage collector knows that no one can reference instance B after leaving the scope, and therefore no one can use instance B to indirectly refer to A.

+4
Jan 12 '12 at 18:48
source share



All Articles