Volatile Fields

 

1)有時,對於只是讀寫一兩個實例數據成員就使用synchronization看起來代價有些過大。如果不使用,又能怎麼樣呢。不幸地是對於現代的多處理器的機器或者當代的編譯器,有太多錯誤的可能:

   多處理器的機器可以把內存變量臨時存放在寄存器或者本地線程緩存中,結果,在不同處理器中運行的線程可能會對於同一個內存地址卻看到不同的值。

 

   編譯器可以整理代碼以提高效率,編譯器不會改變代碼的含義,但是他們會假設同存中的值會被改變當且僅當他們會明確地在代碼中被改變。然而,這些值可能會被其他線程改變,這樣就產生了問題

2) Compilers are required to respect locks by flushing local caches as

 

necessary and not inappropriately reordering instructions

 詳見 the Java Memory Model and Thread Specification developed by JSR 133

3)使用AtomicBoolean

   There are a number of wrapper classes in the java.util.concurrent.atomic

package for atomic integers, floating point numbers, arrays, and so on. These classes are

intended for systems programmers who produce concurrency utilities, not for the appli-

cation programmer.

4)在java 5.0以前,volatile 的語義是非常寬鬆的,語言的設計者們試着去給(虛擬機?)實現者們更大的自由來提高使用volatile fields的代碼的性能。但是,過去的java specification是如此的複雜以致於實現者們並不總是去遵守它,這導致產生了另人迷惑的,不確定的行爲。

例如 immutable objects 表現爲並不是真的"不變"

Prior to Java SE 5.0, the semantics of volatile were rather permissive. The lan-

guage designers attempted to give implementors leeway in optimizing the performance of

code that uses volatile fields. However, the old specification was so complex that implemen

tors didn’t always follow it, and it allowed confusing and undesirable behavior, such as

immutable objects that weren’t truly immutable. 

5)

In summary, concurrent access to a field is safe in these three conditions:

• The field is final, and it is accessed after the constructor has completed.

• Every access to the field is protected by a common lock.

• The field is volatile.

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章