Torkel Franzen said:
The thread seems to have petered out, but I would like to return
to this topic.
The relevant passage in JLS is in 8.1.3:
Any local variable, formal method parameter or exception handler
parameter used but not declared in an inner class must be declared
final.
To understand the rationale behind this requirement, I would like to
see some examples of what could go wrong or would become troublesome
without it.
If this requirement were not true, then the obvious behavior for
accessing a non-final local variable would be that the variable is
shared between the local method context and the inner class. That is,
if one changes the value, the change is visible from the other.
This obvious behavior suffers from two faults: (1) it's complex to
implement and has potentially hidden performance costs, and (2) it
breaks the assumption that local variables never contain shared state
and access to them never need to be synchronized. To avoid these
faults, the requirement was added that they be final... which guarantees
that one possible implementation is for them to be copied into the inner
class; easy to implement, and no threading issues.
The final keyword is required, rather than implying a copy, for two
reasons. First, least surprise as hinted in my first paragraph above.
Second, it leaves an opening for implementing mutable local variables by
transparently encapsulating the locals into an object on the heap when
the method is called. I'm unsure whether this is a good idea and Sun
may never do it; but it could be done compatibly just by lifting the
final requirement for local variables and parameters.
--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation