1. 程式人生 > >同步和Java記憶體模型 (二)原子性

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

作者: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.


程曉明

程曉明,Java軟體工程師,專注於併發程式設計,就職於富士通南大。個人郵箱:[email protected]