capturing (or not) mutable local variables
Brian Goetz
brian.goetz at oracle.com
Sat Nov 20 12:44:09 PST 2010
> 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.
(Some would go farther and say such side-effects in general are bad.)
> And the pattern of using a single element array
> or an AtomicReference wrapper is dangerous and should be discouraged?
Single-element array is disastrous since it seeks only to subvert the rules and doesn't provide needed synchronization. A (final) AtomicXxx might be OK, provided you used compareAndSet correctly for updates, since a final reference to a mutable thread-safe object is fair game (the thread-safe part is key.)
The real offender is primitives. Adding up integers without even considering thread-safety is just so tempting....
More information about the lambda-dev
mailing list