java重排序_Java内存模型FAQ(四)重排序意味着什么?
譯者:Alex
在很多情況下,訪問一個程序變量(對象實例字段,類靜態字段和數組元素)可能會使用不同的順序執行,而不是程序語義所指定的順序執行。編譯器能夠自由的以優化的名義去改變指令順序。在特定的環境下,處理器可能會次序顛倒的執行指令。數據可能在寄存器,處理器緩沖區和主內存中以不同的次序移動,而不是按照程序指定的順序。
例如,如果一個線程寫入值到字段a,然后寫入值到字段b,而且b的值不依賴于a的值,那么,處理器就能夠自由的調整它們的執行順序,而且緩沖區能夠在a之前刷新b的值到主內存。有許多潛在的重排序的來源,例如編譯器,JIT以及緩沖區。
編譯器,運行時和硬件被期望一起協力創建好像是順序執行的語義的假象,這意味著在單線程的程序中,程序應該是不能夠觀察到重排序的影響的。但是,重排序在沒有正確同步了的多線程程序中開始起作用,在這些多線程程序中,一個線程能夠觀察到其他線程的影響,也可能檢測到其他線程將會以一種不同于程序語義所規定的執行順序來訪問變量。
大部分情況下,一個線程不會關注其他線程正在做什么,但是當它需要關注的時候,這時候就需要同步了。
原文
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.
總結
以上是生活随笔為你收集整理的java重排序_Java内存模型FAQ(四)重排序意味着什么?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 安卓极品飞车14下载(安卓极品飞车14)
- 下一篇: linux服务器操作系统(linux服务