Firstly, I know that volatile does not do multiple operations (like i++ ) atomic. This question is about a single read or write operation.
My initial understanding was that volatile only strengthens the memory barrier (i.e. other threads will be able to see updated values).
Now I noticed that the JLS section 17.7 says that volatile additionally does one read or write of an atom. For example, given two streams, both write a different value to volatile long x , then x will finally be one of the values.
I am curious how this is possible. In a 32-bit system, if two streams are written to a 64-bit location in parallel and without the โcorrectโ synchronization (i.e., some kind of blocking), it should be possible for the result to be mixed. For clarity, let me use an example in which stream 1 writes 0L, while stream 2 writes -1L to the same 64-bit memory location.
T1 writes lower 32 bit T2 writes lower 32 bit T2 writes upper 32 bit T1 writes upper 32 bit
The result may be 0x0000FFFF, which is undesirable. How volatile prevent this scenario?
I also read elsewhere that this usually does not degrade performance. How can I synchronize recordings with little impact of speed?
source share