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?
A
cannot depend onB
, becauseA
must get made first, as a member ofB
, and soA
can only hold a weak reference toB
. Thus it is safe to destroyB
first and thenA
. Arguing recursively, every computer program must be thus. There can never be a true, fully symmetric circular dependence. – Kerrek SBwhy do we use WeakReference class? What is its purpose?
I use it -for example- for caching data(in a dictionary). If it is alive ,good, if not, I load it again at first request. – L.B