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?

At least logically one of the references is always going to be weak: In your example, cleary A cannot depend on B, because A must get made first, as a member of B, and so A can only hold a weak reference to B. Thus it is safe to destroy B first and then A. Arguing recursively, every computer program must be thus. There can never be a true, fully symmetric circular dependence.
–
Kerrek SBJan 12 '12 at 18:50

@KerrekSB: I agree with that logic. But that is viewed from the point of creation. Is the GC going to analyse this (i.e the code in each methods of such classes, after all only then it can reach at that conclusion)? I mean, if you see the objects after they've been created, then it looks very much problematic.
–
NawazJan 12 '12 at 18:55

why 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.BJan 12 '12 at 18:57

1

@KerrekSB I don't really get your point. It does not matter when they are created, if they use one another to perform any action, they depend on each other. Memory at A points to B, memory at B points to A. This is circular reference no? At any one state, you are either at A or at B. It does not matter that you were at A first, or second. Unless you are referring to some mathematical notion I am not aware of, I very well think it is perfectly right to refer to this as Circular Reference.
–
didibusOct 23 '12 at 17:33

If a group of objects contain references to each other, but none of
these object
are referenced directly or indirectly from stack or shared variables, then garbage
collection will automatically reclaim the memory.

Several answers already explained that circular references are not a problem.

As to the weak references - the reason to use them is caching.

When GC walks object dependency trees he ignores weak references. In other words if the only reference to an object is a weak one(s), it will be garbage collected, but if there was no garbage collection between reference creation and your attempt to use, you can still access the object.