A memory barrier is a conceptual “line” in your code that prevents the compiler from making certain optimizations and can insert special “synchronizing” commands into the processor. Typically, the compiler can look within a particular method and see that some instructions can be moved without changing the code value. For example, if you have
int x = 0, y = 0; x++; y++;
If the compiler realized that there was any benefit, it might instead output code for
y++; x++;
However, if x and y are fields in some class so that they can be seen from other threads, another thread may change values while your method is running.
The memory limit forces the compiler to double-check the values of specific variables (in Java, those that are volatile and Atomic* ), if some other thread changes them when the method starts and it does not allow the compiler to reorder, which can accidentally change the calculation results. On systems supporting multiple cores / processors, the compiler will also force the processor to check that another processor or hardware device does not change the variable at the same time. Java (on Java 5) has an extremely well-defined set of rules for how this works before it happens .
There are some helpful explanations in this FAQ that were written at the time the Java memory model was being developed. Please note that although the concept of a memory barrier is cross-linguistic, most languages do not have as clearly defined rules about them as Java.
chrylis
source share