Java記憶體模型FAQ(四)重排序意味著什麼?

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

在很多情況下,訪問一個程式變數(物件例項欄位,類靜態欄位和陣列元素)可能會使用不同的順序執行,而不是程式語義所指定的順序執行。編譯器能夠自由的以優化的名義去改變指令順序。在特定的環境下,處理器可能會次序顛倒的執行指令。資料可能在暫存器,處理器緩衝區和主記憶體中以不同的次序移動,而不是按照程式指定的順序。

例如,如果一個執行緒寫入值到欄位a,然後寫入值到欄位b,而且b的值不依賴於a的值,那麼,處理器就能夠自由的調整它們的執行順序,而且緩衝區能夠在a之前重新整理b的值到主記憶體。有許多潛在的重排序的來源,例如編譯器,JIT以及緩衝區。

編譯器,執行時和硬體被期望一起協力建立好像是順序執行的語義的假象,這意味著在單執行緒的程式中,程式應該是不能夠觀察到重排序的影響的。但是,重排序在沒有正確同步了的多執行緒程式中開始起作用,在這些多執行緒程式中,一個執行緒能夠觀察到其他執行緒的影響,也可能檢測到其他執行緒將會以一種不同於程式語義所規定的執行順序來訪問變數。

大部分情況下,一個執行緒不會關注其他執行緒正在做什麼,但是當它需要關注的時候,這時候就需要同步了。

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

原文

What is meant by reordering?

There are a number of cases in which accesses to program variables (object instance fields, class static fields, and array elements) may appear to execute in a different order than was specified by the program. The compiler is free to take liberties with the ordering of instructions in the name of optimization. Processors may execute instructions out of order under certain circumstances. Data may be moved between registers, processor caches, and main memory in different order than specified by the program.

For example, if a thread writes to field a and then to field b, and the value of b does not depend on the value of a, then the compiler is free to reorder these operations, and the cache is free to flush b to main memory before a. There are a number of potential sources of reordering, such as the compiler, the JIT, and the cache.

The compiler, runtime, and hardware are supposed to conspire to create the illusion of as-if-serial semantics, which means that in a single-threaded program, the program should not be able to observe the effects of reorderings. However, reorderings can come into play in incorrectly synchronized multithreaded programs, where one thread is able to observe the effects of other threads, and may be able to detect that variable accesses become visible to other threads in a different order than executed or specified in the program.

Most of the time, one thread doesn’t care what the other is doing. But when it does, that’s what synchronization is for.



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

相關文章