Live objects and dead objects - the basics

suggest change

Rule of thumb: when garbage collection occurs, “live objects” are those still in use, while “dead objects” are those no longer used (any variable or field referencing them, if any, has gone out of scope before the collection occurs).

In the following example (for convenience, FinalizableObject1 and FinalizableObject2 are subclasses of FinalizableObject from the example above and thus inherit the initialization / finalization message behavior):

var obj1 = new FinalizableObject1(); // Finalizable1 instance allocated here
var obj2 = new FinalizableObject2(); // Finalizable2 instance allocated here
obj1 = null; // No more references to the Finalizable1 instance
GC.Collect();
GC.WaitForPendingFinalizers();

If the types use the base messages from the earlier example ("Instance initialized" / "Instance finalized"), the output is:

Instance initialized
Instance initialized
Instance finalized

Those lines do not name the type. At the collection, the FinalizableObject1 instance is dead and is finalized. The FinalizableObject2 instance is still live, so it stays on the managed heap. GC.Collect alone does not wait for that finalizer; WaitForPendingFinalizers does.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents