原子变量是否可以保证内存可见性? [英] Does atomic variables guarantee memory visibility?

查看:608
本文介绍了原子变量是否可以保证内存可见性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于内存可见性的小问题.

Small question about memory visibility.

CodeSample1:

class CustomLock {

    private boolean locked = false;

    public boolean lock() {
        if(!locked) {
            locked = true;
            return true;
        }
        return false;
    }
}

此代码在多线程环境中容易出错,首先是因为"if-then-act"不是原子的,其次是由于潜在的内存可见性问题,例如threadA将字段设置为true,但是后来希望读取该字段值的threadB可能看不到该值,而仍然看到该值为false.

This code is prone to bugs in a multi-threaded environment, first because of the "if-then-act" which is not atomic, and second because of potential memory visibility issues where for example threadA sets the field to true, but threadB that later wishes to read the field's value might not see that, and still see the value false.

最简单的解决方法是使用CodeSample2中的synced关键字.

The simplest solution is to use the synchronized keyword, as in CodeSample2.

CodeSample2:

class CustomLock {

    private boolean locked = false;

    public synchronized boolean lock() {
        if(!locked) {
            locked = true;
            return true;
        }
        return false;
    }
}

现在,如果我希望使用原子变量,例如,一个AtomicBoolean(问题适用于所有原子变量),怎么办?

Now what if I wish to use an atomic variable, and for the example, an AtomicBoolean (question applies to all atomic variables),

CodeSample3:

   public static class CustomLock {
    private AtomicBoolean locked = new AtomicBoolean(false);

    public boolean lock() {
        return locked.compareAndSet(false, true);
    }
}

除了更好的性能考虑之外,我们还可以看到,现在我们已经使用AtomicBoolean实现了与 CodeSample1 中的"if-then-act"类似的逻辑. 逻辑上代码的作用并不重要, 我的问题是 如果2个线程在 CodeSample3 中调用lock()方法会怎样?大约在同一时间,虽然很明显,现在对该字段的任何写操作都将自动完成,但是AtomicBoolean的使用是否还可以保证内存可见性?

Better performance considerations aside, we can see that now we've implemented similar logic to the "if-then-act" from CodeSample1, using AtomicBoolean. It doesn't really matter what the code does logically, the question I have is what if 2 threads invoke the lock() method in CodeSample3 right about the same time, while it's clear that any write operation to the field will now be done atomically, does the use of AtomicBoolean also guarantees memory visibility?

很抱歉,长话短说,只是想确保我能尽可能清楚地看到我,谢谢大家……

Sorry for the long story, just wanted to make sure I'm coming across as clear as possible, Thanks guys...

推荐答案

是的,根据

compareAndSet和所有其他读取和更新操作(例如getAndIncrement)具有读取和写入易失性变量的存储效果.

compareAndSet and all other read-and-update operations such as getAndIncrement have the memory effects of both reading and writing volatile variables.

这篇关于原子变量是否可以保证内存可见性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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