Nice to @Share?
Joshua Bloch
jjb at google.com
Tue Feb 23 00:23:46 PST 2010
Zdenek,
On Tue, Feb 23, 2010 at 12:08 AM, Zdenek Tronicek <tronicek at fit.cvut.cz>wrote:
> Joshua Bloch napsal(a):
> >> I understood that non mutable state actually has to be declared final
> if
> >> you want to share it across threads reliably without using
> >> synchronization.
> >> Merely not modifying it isn't sufficient.
> > This is a complex topic. It turns out that if an object is "strongly
> immutable" (like String), you can share references to it with no
> synchronization whatsoever.If you're morbidly curious, this is a good
> place
> > to start: http://www.cs.umd.edu/~pugh/java/memoryModel/ .
>
> In some sense, Mark is right. Of course, you can share strongly immutable
> objects without any synchronization. But how to share the reference? If
> one thread stores a reference to a shared variable, how do you ensure that
> such change is visible in another thread? You need a barrier and this is
> probably where the hint "make the shared variables final" comes from.
Believe it or not, you don't. For example, you can have one thread create a
new String, jam a reference to it into a public static variable, and another
thread can safely read the String. You should pretty much never do this,
but it was a constraint in the design of the memory model: Java relies on
immutability of String (and Integer, and the like), even if references are
shared willy-nilly. That said, ordinary humans should "synchronize" all
access to shared mutable state (where synchronize is broadly defined). "Just
because you can doesn't mean you should."
Josh
More information about the lambda-dev
mailing list