Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Garbage collector and circular reference

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 classes designed like above, would the objects of such classes be collected by 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 were to collect it, it would have to collect a first which is the member of B, and to collect a, it needs to collect b first which is the member of A. It becomes circular. So my question is : is such circular reference going to prevent GC from collecting the objects?

  • If yes, then how can we avoid this problem? How can we make sure that we don't have circular reference in our class design? Is there any tool (or compiler option) that helps us detecting circular reference?
  • If no, where and why do we use WeakReference class? What is its purpose?
like image 491
Nawaz Avatar asked Jan 12 '12 18:01

Nawaz


People also ask

Does garbage collector handle cyclic references?

yes Java Garbage collector handles circular-reference!

How does garbage collector resolves circular reference issue?

To handle the problem of circular references in C#, you should use garbage collection. It detects and collects circular references. The garbage collector begins with local and static and it marks each object that can be reached through their children. Through this, you can handle the issues with circular references.

Can garbage collector release isolate circular references?

The . NET garbage collector can absolutely handle circular references.

Is garbage collection based on reference?

Reference counting garbage collection is where each object has a count of the number of references to it. Garbage is identified by having a reference count of zero. An object's reference count is incremented when a reference to it is created, and decremented when a reference is destroyed.


1 Answers

The .Net garbage collector can absolutely handle circular references. The very high level view of how the garbage collector works is ...

  • Start with locals, statics and GC pinned objects. None of these can be collected
  • Mark every object which can be reached by traversing the children of these objects
  • Collect every object which is not marked.

This allows for circular references to be collected just fine. So long as none of them are reachable from an object known to be uncollectable then the circular reference is essentially irrelevant.

Note: I realize I've left out many fun details in order to keep this answer simple and direct

like image 178
JaredPar Avatar answered Sep 18 '22 14:09

JaredPar