In theory any local variable ceases to be a GC root as soon as it goes out of scope. (Even if there is non-local access to the variable via a nested class, etc. In that case, the value in the variable will have copied into another (synthetic) variable with a longer lifetime.)
In practice, the JVM may actually wait until the enclosing method call returns. It is implementation dependent.
But it your example:
- Those local variables could be optimized away by the JIT compiler.
- They are primitive variables, so they don't hold references to objects anyway. The GC won't pay any attention to them.
In general, you wouldn't normally worry about this. It rarely matters that a few variables become unreachable a bit later than is strictly necessary.
However consider the following:
public static void longRunningMethod() {
// do stuff
{
Map<X, Y> bigMap = ... // create and populate a huge map
// use bigMap
bigMap = null;
}
// long running computation
}
If you had clear evidence of a "garbage retention" problem due to bigMap
, you might consider assigning null
to it, as above. On the other hand, that assignment could also be a candidate for being optimized away!