Java内存模型FAQ(四)重排序意味着什么?
在很多情況下,訪問(wèn)一個(gè)程序變量(對(duì)象實(shí)例字段,類靜態(tài)字段和數(shù)組元素)可能會(huì)使用不同的順序執(zhí)行,而不是程序語(yǔ)義所指定的順序執(zhí)行。編譯器能夠自 由的以優(yōu)化的名義去改變指令順序。在特定的環(huán)境下,處理器可能會(huì)次序顛倒的執(zhí)行指令。數(shù)據(jù)可能在寄存器,處理器緩沖區(qū)和主內(nèi)存中以不同的次序移動(dòng),而不是 按照程序指定的順序。
例如,如果一個(gè)線程寫(xiě)入值到字段a,然后寫(xiě)入值到字段b,而且b的值不依賴于a的值,那么,處理器就能夠自由的調(diào)整它們的執(zhí)行順序,而且緩沖區(qū)能夠在a之前刷新b的值到主內(nèi)存。有許多潛在的重排序的來(lái)源,例如編譯器,JIT以及緩沖區(qū)。
編譯器,運(yùn)行時(shí)和硬件被期望一起協(xié)力創(chuàng)建好像是順序執(zhí)行的語(yǔ)義的假象,這意味著在單線程的程序中,程序應(yīng)該是不能夠觀察到重排序的影響的。但是,重 排序在沒(méi)有正確同步了的多線程程序中開(kāi)始起作用,在這些多線程程序中,一個(gè)線程能夠觀察到其他線程的影響,也可能檢測(cè)到其他線程將會(huì)以一種不同于程序語(yǔ)義 所規(guī)定的執(zhí)行順序來(lái)訪問(wèn)變量。
大部分情況下,一個(gè)線程不會(huì)關(guān)注其他線程正在做什么,但是當(dāng)它需要關(guān)注的時(shí)候,這時(shí)候就需要同步了。
原文
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.
轉(zhuǎn)載于:https://blog.51cto.com/chenyanxi/1558526
總結(jié)
以上是生活随笔為你收集整理的Java内存模型FAQ(四)重排序意味着什么?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: iOS会议和组织
- 下一篇: openssh-在win7上的搭建