Effectively final

Roel Spilker r.spilker at gmail.com
Wed Aug 17 01:53:30 PDT 2011


>
>
> Put your 2 paragraphs together and you have your answer:  The container
> object *is* the inner class instance.  The compiler translates both
> reads and
> writes of the variable to reads and writes of the field.
>
>
That won't work since the lifespan of the variable and the closure are not
the same. So you need a different container. Theoretically you might get
away with the stack allocated variable if escape and data flow analysis can
determine that that's safe.


> See "Old closure implementation" here:
> http://www.gnu.org/software/kawa/internals/procedures.html
>
> A complication (and a difference between Scheme and Java) is handling
> loops:
>
> int sum = 0;
> for (;;) {
>    int v = ...;
>    do_something_with((x)->{sum+=v;});
> }
>
> Putting the sum field in the lambda inner class doesn't work if there
> are multiple inner class instances for a captured variable.  In the
> general case you might need an extra compiler-generated container object.
>
>
Agreed


> > .... These are all cool things. And complicated.
> >
> > By restricting the use of local variables to final local variables for
> now,
> > the ways for possible future enhancements remain open.
>
> I tend to agree.  I would prefer to allow mutable local variable
> capture, but it makes sense to defer it to post-Java8.
>

I would also prefer to allow mutable local variable capture, but only if the
developer explicitly publishes it.

Roel


More information about the lambda-dev mailing list