How can I use the volatile keyword in Java correctly?

前端 未结 6 1987
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 14:31

Say I have two threads and an object. One thread assigns the object:

public void assign(MyObject o) {
    myObject = o;
}

Another thread uses t

6条回答
  •  广开言路
    2021-02-05 15:21

    There are some confusing comments here: to clarify, your code is incorrect as it stands, assuming two different threads call assign() and use().

    In the absence of volatile, or another happens-before relationship (for example, synchronization on a common lock) any write to myObject in assign() is not guaranteed to be seen by the thread calling use() -- not immediately, not in a timely fashion, and indeed not ever.

    Yes, volatile is one way of correcting this (assuming this is incorrect behaviour -- there are plausible situations where you don't care about this!).

    You are exactly correct that the 'use' thread can see any 'cached' value of myObject, including the one it was assigned at construction time and any intermediate value (again in the absence of other happens-before points).

提交回复
热议问题