capturing (or not) mutable local variables

Alessio Stalla alessiostalla at gmail.com
Mon Nov 22 04:21:12 PST 2010


On Mon, Nov 22, 2010 at 9:17 AM, Rémi Forax <forax at univ-mlv.fr> wrote:
>  Le 22/11/2010 08:57, Howard Lovatt a écrit :
>
> [...]
>
>> Tell people that if they want mutable state they should use AtomicXXX
>> to guarantee thread safety. It is a pity that Java didn't make
>
> Using AtomicXXX is not a good idea too.
>
> By example, if you want to sum a collection of integers using an atomic
> variable, this means the volatile variable (inside the atomic class) will be updated
> for each element.
>
> If you use a map/reduce pattern, you only need one synchronization point
> at the end of the calculation so the map/reduce code outperforms
> the solution with an atomic variable.

I'd like to point out that, in my experience with Lisp, the mutability
of the closed-over variables is rarely if ever used to update a local
to be used further down the same function/method; in other words,

int i = 0;
foo.foreach(#{ x -> i += x; });
use(i);

is not a common code pattern, and it's generally considered bad style.
Instead, mutable captured variables are used much more often as a way
to give some private state to a closure, effectively turning it into a
lightweight object (in the OO sense). So, while I do believe that
"true" closures should close over their lexical environment without
restrictions, including mutability, I think in Java the issue
isn't/won't be that important; if you want private state you can still
use a plain old inner class and explicitly capture (copy) the locals
you're interested in -  after all, closures are going to be "syntax
sugar" for SAM types anyway - or you can use final/effectively final
(+ maybe AtomicXxx if you need it).


More information about the lambda-dev mailing list