天天看點

java volatile double、long的原子性

同步和Java記憶體模型 (二)原子性

原文:http://gee.cs.oswego.edu/dl/cpj/jmm.html 第二章

作者:Doug Lea 譯者:程曉明  校對:方騰飛

除了long型字段和double型字段外,java記憶體模型確定通路任意類型字段所對應的記憶體單元都是原子的。這包括引用其它對象的引用類型的字段。此外,volatile long 和volatile double也具有原子性 。(雖然java記憶體模型不保證non-volatile long 和 non-volatile double的原子性,當然它們在某些場合也具有原子性。)(譯注:non-volatile long在64位JVM,OS,CPU下具有原子性)

當在一個表達式中使用一個non-long或者non-double型字段時,原子性可以確定你将獲得這個字段的初始值或者某個線程對這個字段寫入之後的值;但不會是兩個或更多線程在同一時間對這個字段寫入之後産生混亂的結果值(即原子性可以確定,擷取到的結果值所對應的所有bit位,全部都是由單個線程寫入的)。但是,如下面(譯注:指可見性章節)将要看到的,原子性不能確定你獲得的是任意線程寫入之後的最新值。 是以,原子性保證通常對并發程式設計的影響很小。

原文

Atomicity

Accesses and updates to the memory cells corresponding to fields of any type except long or double are guaranteed to be atomic. This includes fields serving as references to other objects. Additionally, atomicity extends to volatile long and double. (Even though non-volatile longs and doubles are not guaranteed atomic, they are of course allowed to be.)

Atomicity guarantees ensure that when a non-long/double field is used in an expression, you will obtain either its initial value or some value that was written by some thread, but not some jumble of bits resulting from two or more threads both trying to write values at the same time. However, as seen below, atomicity alone does not guarantee that you will get the value most recently written by any thread. For this reason, atomicity guarantees per se normally have little impact on concurrent program design.