How can I use the volatile keyword in Java correctly?

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

    I am trying to understand when to use volatile and when not

    You should mostly avoid using it. Use an AtomicReference instead (or another atomic class where appropriate). The memory effects are the same and the intent is much clearer.

    I highly suggest reading the excellent Java Concurrency in Practice for a better understanding.

提交回复
热议问题