How can I use the volatile keyword in Java correctly?

前端 未结 6 1978
没有蜡笔的小新
没有蜡笔的小新 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:32

    You can use volatile in this case. You will require volatile, synchronization around the access to the variable or some similar mechanism (like AtomicReference) to guarantee that changes made on the assignment thread are actually visible to the reading thread.

提交回复
热议问题