I suppose that a program like this…
class Test {
public static void main(String[] args) {
new Test();
System.out.println("done");
}
protected void finalize() {
System.out.println("this object is known to never be referenced.");
}
}
…may possibly output "this object is known to never be referenced." before "done". (Correct me if I’m wrong here!)
Furthermore, it is easy for a compiler/JVM to detect “unread locals”. In the program below for instance, Eclipse notices that “The local variable t is never read“.
However would it be illegal for the JVM to output "this object is known to never be referenced." before "done" given the (.class version) of the program below?
class Test {
public static void main(String[] args) {
Test t = new Test();
System.out.println("done");
}
protected void finalize() {
System.out.println("this object is known to never be referenced.");
}
}
Most documentation of garbage collection talk about reachability. Given the fact that t is never read, the object is obviously not “reachable”, or?
References to the JLS are appreciated.
In 12.6.1 of the Java Language Specification says:
The last phrase seems to me covering exactly the case you are asking about. The variable
tcan be set tonullimplicitly before the end of the scope, therefore making the object unreachable.This in C++ would be a disaster because a lot of code depends on exact destruction timing at the end of scope (e.g. for locks).