Let's assume I have the following code:
public void myMethod() {
final Object x = new Object();
// I never refer to x.
// other code, for example:
System.out.println("lala");
}
The question I have is: what is the earliest possible moment that x can be garbage collected?
I have checked the JLS and JVM spec, but I cannot find the answer. It seems to me, that the assignment to x causes a local variable slot in the stack frame to be assigned a reference to x, and therefore, x cannot be garbage collected until after the method returns since there is a strong reference to x during the entire method call. But maybe the compiler might be allowed to compile away the unused local variable, resulting simply in the code: new Object(), which would then create an object which immediately has no strong references, and can be collected before the println. Does anybody know the correct answer?
Regards,
Sebastiaan