capturing (or not) mutable local variables

Brian Goetz brian.goetz at oracle.com
Mon Nov 22 16:08:08 PST 2010


> final List square = new ArrayList();
> list.forEach(#{ e ->  square.add(e*e); });
>
> How is that really different from your simple broken example? Why
> would we be ok with that one, but not with yours? Should not we be all
> equally screaming 'please do not make this non thread safe closure
> passable to this multithreaded method'?.

One significant difference is that the reference-based version *can* be made 
thread-safe by making the referent thread-safe (say, by replacing "new 
ArrayList()" with "Collections.synchronizedList(new ArrayList())").  The 
primitive version cannot realistically be made thread-safe.

(Effectively, you have provided the argument why we should not have a 
list.forEach() all -- it demands that the client use side-effects to achieve 
the desired results, which invites trouble.)

In any case, I think it is time to close this discussion.  You've made your 
point, some people agree with you, and some others disagree.  But we do not 
intend to lift this restriction at this time, and I don't think further 
discussion will bring to light any issues that have not already been 
considered.  We can always revisit this issue in a future iteration (choosing 
not to lift a restriction now does not foreclose on our ability to do so later).




More information about the lambda-dev mailing list