capturing (or not) mutable local variables

Jim Mayer jim at pentastich.org
Sun Nov 21 14:41:09 PST 2010


I completely agree with Mr. Bothner's analysis.

If I understand correctly, the motivation for disallowing access to mutable
local variables is to make libraries that transparently use multiple threads
(e.g., parallel array operations) safer.  I think the restriction
unnecessarily limits the functionality of closures in the (far more common
today) single-threaded cases and is insufficient to make the multi-threaded
case actually safe.

I like the idea of an annotation on methods (@Parallel?) that could be used
by the compiler on a
"best effort" basis to warn of common unsafe practices (e.g., any
unsynchronized access to mutable state) would help.  I assume that's been
proposed and debated many times already, though :-)

--- Jim


On Sun, Nov 21, 2010 at 3:18 PM, Per Bothner <per at bothner.com> wrote:

> On 11/20/2010 12:44 PM, Brian Goetz wrote:
> >> I think I'm hearing that mutating a local variable from a closure is
> just a
> >> bad idea in general right?
> >
> > For a closure that might conceivably be executed in another thread, this
> is correct.
>
> Agreed - but how is that different from mutating a field or array element
> from a closure that might conceivably be executed in another thread?
> You're just forcing the user to do by hand to work around a restriction.
>
> Note this is not a restriction in any other language I know that has
> both closures and mutable local variables.  The traditional concept of
> lexical scoping (as in Lisp and Scheme) is that closures capture
> local bindings.  If you disallow closing over mutable locals,
> then you only provide a restricted subset of closures.
>
> Of course having multiple threads invoking a closure that can
> mutate a variable is Bad, but what I'm not getting how this is
> different from multiple threads invoking a method that mutate
> a field.  Yes, it might be nice to have a language that protects
> against the latter - but that is different language than Java.
>
> > Single-element array is disastrous since it seeks only to subvert the
> rules and doesn't provide needed synchronization.
>
> Which leads to the question: Since the rules as so trivially
> subvertable, why have the
> rules, since that they complicate real use-cases?  Java really isn't a
> language
> for true multi-threaded programming - it's a language where multiple
> threads
> can co-ordinate with each other (when using appropriate care).  So making
> "multiple threads" the justification for this restriction doesn't really
> make multi-threaded programming easier or safer.
> --
>        --Per Bothner
> per at bothner.com   http://per.bothner.com/
>
>


More information about the lambda-dev mailing list