atomicity and volatile

来源:互联网 发布:终极一班武器淘宝 编辑:程序博客网 时间:2024/05/23 18:41

http://stackoverflow.com/questions/362740/java-memory-model-can-someone-explain-it

I will offer some insight on just one aspect, because it's often misunderstood:

There's a difference between volatility and atomicity. People often think that an atomic write is volatile (i.e. you don't need to worry about the memory model if the write is atomic). That's not true.

Volatility is about whether one thread performing a read (logically, in the source code) will "see" changes made by another thread.

Atomicity is about whether there is any chance that if a change is seen, only part of the change will be seen.

For instance, take writing to an integer field. That is guaranteed to be atomic, but not volatile. That means that if we have (starting at foo.x = 0):

Thread 1: foo.x = 257;Thread 2: int y = foo.x;

It's possible for y to be 0 or 257. It won't be any other value, (e.g. 256 or 1) due to the atomicity constraint. However, even if you know that in "wall time" the code in thread 2 executed after the code in thread 1, there could be odd caching, memory accesses "moving" etc. Making the variable x volatile will fix this.