When defining a local inner class, is it safe to access local variables of the containing method that only said class has references to. Like so:
public Bar containingMethod()
{
Foo foo = new Foo();
Bar bar = new Bar()
{
public void baz()
{
System.out.println("Accessing foo: " + foo.getValue());
}
};
return bar;
};
In my example above I’m not sure that the class being defined has a reference to foo. The question is if it’s safe and OK to do this or am I running the risk of foo being garbage collected before bar.baz() is called?
It is safe, but foo needs to be final (otherwise you should get a compile error).
Foo will not be garbage collected, because under the hood, bar will contain a reference to it.
The reason for foo needing to be final is to avoid this hidden reference getting out of sync.
From a garbage-collection standpoint, it would be safe even without foo being final. But the reference to foo that bar holds is assigned when you create bar, and never updated, so if the containing method were allowed to assign something else to foo later, bar would still see the “old” object.
Note that the requirement to be final only applies to local variables and parameters, not to instance fields of the containing class.