views:

99

answers:

1

Will garbage collector free resources for cross referenced object/class, which is no longer referenced from main program. For example -

class class1
{
    class2 m_RefClass2;
}
class class2
{
    class1 m_RefClass1;
}

class class3
{
    public class3()
    {
        class1 obj1 = new class1();
        class2 obj2 = new class2();
        obj1.m_RefClass2 = obj2;
        obj2.m_RefClass1 = obj1;
    }
}
+6  A: 

Yes. The .NET garbage collector is not simply counting references (in which case such an arrangement would cause both classes to keep each other alive). Any object that is not "rooted" (meaning that there is no reference path to the object from a GC root object) is eligible for collection.

Adam Robinson
beat me by 16 seconds
Joel Coehoorn
If I had a nickel for every time I've heard that!
Adam Robinson
THNX! One more thing - when will GC decide to free these resources? Does it happec offten or rare (like when closing program?)
0xDEAD BEEF
@0xDEAD BEEF: It's impossible to determine, and *may never happen*. You can call `GC.Collect` yourself, but don't. Let the GC worry about when to collect your memory.
Adam Robinson
@0xDEAD BEEF: it happens when the GC thinks it is appropriate to happen. And when it happens, it happens "by chunks", not everything in one go. Usually, the GC does a much better job at guessing when it shoud run than most programmers, so please let the GC run at its leisure.
Thomas Pornin
One more question.. :)Say class a references class b, class b references class c and so on.How will GC know, if it should free class Z? Will it go up in reference tree up to class a to find out, that it is referenced somwhere global? And if so- isnt this a huge waste of time?AND one more question - How does weak reference works. Simply put - when GC frees some resource - does it somehow iterates all weak-references and nulls them?
0xDEAD BEEF
@0xDEAD BEEF: I'm not familiar with the specific mechanics of what paths the GC travels to determine the eligibility of an object (ie if it traverses the chain from the object *up*, or if it builds a map of all valid objects by going *down*, then checking to see if individual objects are in that map, or something entirely different that I haven't considered), but no, regardless of the mechanism it isn't a "huge waste of time". Yes, `WeakReference` instances are treated specially and are appropriately updated once the referenced object is collected. Note that you should use `IsAlive` to check.
Adam Robinson