Firstly let me say I am aware that System.gc() is more of a suggestion to collect garbage than a command, and that collection is not guaranteed to finish, start, or collect a specific object. And yet...
With the following code , the a1 instance only gets collected if I explicitly put null in the reference. If a1 simply goes out of scope, it does not get collected.
class A {
@Override
protected void finalize() throws Throwable {
System.out.println("Collecting A");
}
}
public class Example {
public static void main(String[] args) throws InterruptedException {
try {
A a1 = new A();
//a1 = null; // a1 gets collected only if I uncomment this line
}
finally {
System.out.println("Finally executed");
}
System.gc();
Thread.sleep(1000);
}
}
Why does a1 not get collected if it simply goes out of scope, when there are no strong references to it ? Is it because this scope does not constitute a separate stack frame?