我读过“CLR通过C#”,在这个例子中,最初被分配到肥料的物体在一行执行后将有资格获得垃圾收集,而不是在第二行之后。
void Foo()
{
Object obj = new Object();
obj = null;
}
That s because local variable lifespan defined not by scope in which it was defined, but by last time you read it.
So my question is: what about Java? I have written this program to check such behavior, and it looks like object stays alive. I don t think that it s possible for the JVM to limit variable lifetime while interpreting bytecode, so I tried to run program with java -Xcomp to force method compilation, but finalize is not called anyway. Looks like that s not true for Java, but I hope I can get a more accurate answer here. Also, what about Android s Dalvik VM?
class TestProgram {
public static void main(String[] args) {
TestProgram ref = new TestProgram();
System.gc();
}
@Override
protected void finalize() {
System.out.println("finalized");
}
}
Added: Jeffrey Richter gives code example in "CLR via C#", something like this:
public static void Main (string[] args)
{
var timer = new Timer(TimerCallback, null, 0, 1000); // call every second
Console.ReadLine();
}
public static void TimerCallback(Object o)
{
Console.WriteLine("Callback!");
GC.Collect();
}
TimerCallback called only once on MS .Net if projects target is Release (timer destroyed after GC.Collect() call), and called every second if target is Debug (variables lifespan increased because programmer can try to access object with debugger). But on Mono callback called every second no matter how you compile it. Looks like Mono s Timer implementation stores reference to instance somewhere in thread pool. MS implementation doesn t do this.