Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Is it allowed for unused variables to be optimized away by the compiler?

807603Feb 14 2008 — edited Feb 14 2008
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
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 13 2008
Added on Feb 14 2008
9 comments
1,077 views