Jevgeni Kabanov on dow.ngra.de made an interesting observation that I had noticed at one point when I was studying the new Java Memory Model, but that I had forgotten again.
A shared volatile
variable that thread A writes to and thread B subsequently reads from guarantees that thread B sees everything that thread A saw when it wrote to the volatile
variable, even if the other data is not volatile
itself.
The most easily accessible documentation about this is from Bill Pugh’s JSR-133 FAQ:
Under the new memory model, it is still true that volatile variables cannot be reordered with each other. The difference is that it is now no longer so easy to reorder normal field accesses around them. Writing to a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire. In effect, because the new memory model places stricter constraints on reordering of volatile field accesses with other field accesses, volatile or not, anything that was visible to thread A when it writes to volatile field f becomes visible to thread B when it reads f.
Update
A very similar post popped up, Thread-safe non-synchronized read/writes?, and a commenter Matthias (not me, I have just one ‘t’) makes an important point:
Since the revision of the memory model, writing to a ‘volatile’ guarantees that no previous write will be reordered beyond it. Vice versa with reads. That’s why you can use volatiles for synchronization purposes – but only if you both write it in one thread _and_ read it in the other.
(Emphasis added by me).