如何正确使用Java中的volatile关键字? [英] How can I use the volatile keyword in Java correctly?

查看:133
本文介绍了如何正确使用Java中的volatile关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个线程和一个对象。一个线程分配对象:

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

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

另一个线程使用该对象:

Another thread uses the object:

public void use() {
    myObject.use();
}

变量myObject是否必须声明为volatile?我想知道什么时候使用volatile,什么时候不用,这让我很困惑。是否有可能第二个线程在其本地内存缓存中保留对旧对象的引用?如果没有,为什么不呢?

Does the variable myObject have to be declared as volatile? I am trying to understand when to use volatile and when not, and this is puzzling me. Is it possible that the second thread keeps a reference to an old object in its local memory cache? If not, why not?

非常感谢。

推荐答案


我想知道何时使用
volatile而不是

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

你应该主要避免使用它。请改用 AtomicReference (或其他原子适当的课程)。记忆效果相同,意图很多更清晰。

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.

我强烈建议阅读优秀的 Java Concurrency in Practice 以便更好地理解。

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

这篇关于如何正确使用Java中的volatile关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆