This is a mirror of official site: http://jasper-net.blogspot.com/

When does an object become available for garbage collection?

| Wednesday, August 11, 2010
As we saw last time, garbage collection is a method for simulating an infinite amount of memory in a finite amount of memory. This simulation is performed by reclaiming memory once the environment can determine that the program wouldn't notice that the memory was reclaimed. There are a variety of mechanism for determining this. In a basic tracing collector, this determination is made by taking the objects which the program has definite references to, then tracing references from those objects, contining transitively until all accessible objects are found. But what looks like a definite reference in your code may not actually be a definite reference in the virtual machine: Just because a variable is in scope doesn't mean that it is live.

class SomeClass {
...
string SomeMethod(string s, bool reformulate)
{
 OtherClass o = new OtherClass(s);
 string result = Frob(o);
 if (reformulate) Reformulate();
 return result;
}
}
For the purpose of this discussion, assume that the Frob method does not retain a reference to the object o passed as a parameter. When does the OtherClass object o become eligible for collection? A naïve answer would be that it becomes eligible for collection at the closing-brace of the SomeMethod method, since that's when the last reference (in the variable o) goes out of scope.

A less naïve answer would be that it become eligible for collection after the return value from Frob is stored to the local variable result, because that's the last line of code which uses the variable o.

Read more: The old new thing

Posted via email from .NET Info

0 comments: