Nice to @Share?

abies at adres.pl abies at adres.pl
Tue Feb 23 01:06:02 PST 2010


"Joshua Bloch" <jjb at google.com> napisał(a): 

 > 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.

I think that original point was about visibility of the reference update, not about seeing initialized/not-initialized String itself (which indeed is guaranteed in case of proper immutable objects). If both threads are already started and there is no synchronization point between them, thread2 is allowed to NEVER see the update to non-volatile static field done by thread1.

Question is, does it matter to us? I'm not sure if it is possible to do something and then dispatch work on that something to multiple threads using any of the concurrency facilities without performing implicit synchronization. Putting any kind of task to executor/thread pool will create some synchronization point on one of the queues (unless there is some CAS no-lock no-membarrier mojo involved there which will be well over top of my head...).

This means we get consistent state at the beginning. If you mutate the variable in non-trivial way without synchronization/locking from multiple threads afterward, you are in the mess anyway, updates visible or not. Only interesting non-synchronized case would be probably something like boolean initialized to false (or reference from null to something), which is then turned to 'true' if one of the threads hits some condition. But again, in this case, you will probably want to wait for all threads to finish their work before checking the boolean - and again, this 'waiting' will implicitly make the memory right. If you just loop over boolean without explicitly checking if threads are finished... I don't think you deserve a cookie.

Regards,
Artur Biesiadowski


More information about the lambda-dev mailing list