capturing (or not) mutable local variables
Per Bothner
per at bothner.com
Mon Nov 22 11:18:41 PST 2010
On 11/22/2010 03:25 AM, Steven Simpson wrote:
> If it was referenced from a closure or inner class, how would it be made
> mutable? From what I've seen, the only proposals are to box it up in
> some object, e.g. array of 1, or anonymous class. Within that box, it
> could be declared volatile.
If a lambda is implemented as an inner class, then any captured mutable
local variables can be implemented as fields of the closure class. I.e. you
don't need to allocate any extra objects or create new classes.
That means all accesses to the variable (even the ones outside the
closure) get translated to access of the field in the closure.
But, you say, the variable is defined earlier than the closure,
and possibly in an outer scope! The solution: Pre-allocate the
closure when entering the scope of the variable. It gets more
complicated if the closure captures mutable variable from
multiple different scopes, especially if the inner scope is in
a loop - in that case, I think you do have to allocate a helper
object.
I did this for Kawa *before* Java had inner classes - i.e. in the
jdk-1.0 dawn of Java. Look for "Old closure implementation" in:
http://www.gnu.org/software/kawa/internals/procedures.html
--
--Per Bothner
per at bothner.com http://per.bothner.com/
More information about the lambda-dev
mailing list