Java記憶體模型FAQ(五)舊的記憶體模型有什麼問題?

喝水會長肉發表於2021-12-02

舊的記憶體模型中有幾個嚴重的問題。這些問題很難理解,因此被廣泛的違背。例如,舊的儲存模型在許多情況下,不允許JVM發生各種重排序行為。舊的記憶體模型中讓人產生困惑的因素造就了JSR-133規範的誕生。


例如,一個被廣泛認可的概念就是,如果使用final欄位,那麼就沒有必要在多個執行緒中使用同步來保證其他執行緒能夠看到這個欄位的值。儘管這是一個合理的假設和明顯的行為,也是我們所期待的結果。實際上,在舊的記憶體模型中,我們想讓程式正確執行起來卻是不行的。在舊的記憶體模型中,final欄位並沒有同其他欄位進行區別對待——這意味著同步是保證所有執行緒看到一個在構造方法中初始化的final欄位的唯一方法。結果——如果沒有正確同步的話,對一個執行緒來說,它可能看到一個欄位的預設值,然後在稍後的時間裡,又能夠看到構造方法中設定的值。這意味著,一些不可變的物件,例如String,能夠改變它們值——這實在很讓人鬱悶。

舊的記憶體模型允許volatile變數的寫操作和非volaitle變數的讀寫操作一起進行重排序,這和大多數的開發人員對於volatile變數的直觀感受是不一致的,因此會造成迷惑。

最後,我們將看到的是,程式設計師對於程式沒有被正確同步的情況下將會發生什麼的直觀感受通常是錯誤的。JSR-133的目的之一就是要引起這方面的注意。

《Java記憶體模型FAQ(一) 什麼是記憶體模型》

原文

What was wrong with the old memory model?

There were several serious problems with the old memory model. It was difficult to understand, and therefore widely violated. For example, the old model did not, in many cases, allow the kinds of reorderings that took place in every JVM. This confusion about the implications of the old model was what compelled the formation of JSR-133.

One widely held belief, for example, was that if final fields were used, then synchronization between threads was unnecessary to guarantee another thread would see the value of the field. While this is a reasonable assumption and a sensible behavior, and indeed how we would want things to work, under the old memory model, it was simply not true. Nothing in the old memory model treated final fields differently from any other field — meaning synchronization was the only way to ensure that all threads see the value of a final field that was written by the constructor. As a result, it was possible for a thread to see the default value of the field, and then at some later time see its constructed value. This means, for example, that immutable objects like String can appear to change their value — a disturbing prospect indeed.

The old memory model allowed for volatile writes to be reordered with nonvolatile reads and writes, which was not consistent with most developers intuitions about volatile and therefore caused confusion.

Finally, as we shall see, programmers’ intuitions about what can occur when their programs are incorrectly synchronized are often mistaken. One of the goals of JSR-133 is to call attention to this fact.


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/70010294/viewspace-2845380/,如需轉載,請註明出處,否則將追究法律責任。

相關文章