In java, with my knowledge, volatile variable make a thread reads/writes directly to main CPU (not in cache of each thread), so make its change visibles to other threads.
The thing I don’t know is : So, why this work (of volatile) can prevent compiler/CPU reorder statement of code.
thanks 🙂
Here is a very good example illustrating the issue the prohibition on reordering is aimed to address (taken from here):
In this example,
vis volatile, butxis not. If writer and reader are executed concurrently and the reader seesvset totrue,xis guaranteed to be42. Prior to Java-5, compiler was free to re-order the writes toxandv, so you could seexat zero after you’ve seenvset totrue. This was confusing, and lead to subtle errors. Java-5 memory model addressed this issue by making volatile writes almost equivalent to synchronization.