Search code examples
javamultithreading

Happens before guarantee in Volatile


While going through the Java Concurrency in Practice I came across the below statement related to the Happens before guarantee that Volatile provides

Happens before relation when two threads synchronize using a common lock. All the actions within thread A are ordered by the program order rule, as are the actions within thread B. Because A releases lock M and B subsequently acquires M, all the actions in A before releasing the lock are therefore ordered before the actions in B after acquiring the lock. When two threads synchronize on different locks, we can't say anything about the ordering of actions between them there is no happens before relation between the actions in the two threads.

Can someone please elaborate a bit more on what exactly does this mean?


Solution

  • Can someone please elaborate a bit more on what exactly does this mean?

    The quoted text is about the semantics of primitive locks.

    Basically it says that if thread A writes to a shared variable V while holding a lock M, and then releases the lock, and then thread B acquires lock M and reads the shared variable V, then it will not see the value of V before the either before it was written by A.

    It won't necessarily see the value written by A though because it is possible that another C thread wrote to V:

    • If C wrote to V while holding the lock M, then B will see A's value if C's write was at a point in time before A's write.

    • If C wrote to V without holding the lock, then it is unspecified what value B's read will see.

    The semantics of volatile are a bit simpler. If A writes a value to volatile V, and then if B reads V after As write then it won't see the value of V before A's write. (It will either see what A wrote, or something written by some other thread at or after the time of A's write.)