I am looking into how a synchronized and volatile variable works in java and i came across a concept called read and write barrier . Can anyone help me to understand the mea
A memory barrier is a conceptual "line" in your code that prevents the compiler from making certain optimizations and may insert special "sync up" commands to the processor. Normally, the compiler can look within a particular method and see that certain instructions can be moved around without changing the meaning of the code. For example, if you have
int x = 0, y = 0;
x++;
y++;
If the compiler figured that there was some benefit, it could 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, the other thread might be modifying the values while your method is running.
A memory barrier forces the compiler to recheck the values of specific variables (in Java, those are ones that are volatile
and the Atomic*
classes) in case some other thread has modified them while the method's been running, and it keeps the compiler from making reorderings that might accidentally change the results of a calculation. On systems that support multiple cores/processors, the compiler will also force the processor to check to make sure that some other processor or hardware device hasn't modified the variable in the meantime. Java (as of Java 5) has an extremely well-defined set of rules for how this works called happens-before.
This FAQ has some useful explanations that were written at the time the Java Memory Model was being developed. Note that while the concept of a memory barrier is cross-language, most languages don't have as clearly defined rules about them as Java.