java – 显式锁是否自动提供内存可见性?

示例代码:

class Sample{
    private int v;
    public void setV(){
        Lock a=new Lock();
        a.lock();
        try{
            v=1;
        }finally{
            a.unlock();
        }
    }
    public int getV(){
        return v;
    }
}

如果我有一个线程不断调用getV,我只是在另一个线程中执行setV一次,那读取线程是否保证在写入后立即看到新值?还是需要使“V”变化或AtomicReference?

如果答案是否定的,那么我应该把它改成:

class Sample{
    private int v;
    private Lock a=new Lock();
    public void setV(){
        a.lock();
        try{
            v=1;
        }finally{
            a.unlock();
        }
    }
    public int getV(){
        a.lock();
        try{
            int r=v;
        }finally{
            a.unlock();
        }
        return r;
    }
}

解决方法


documentation:

All Lock implementations must enforce the same memory synchronization semantics as provided by the built-in monitor lock:

  • A successful lock operation acts like a successful monitorEnter action
  • A successful unlock operation acts like a successful monitorExit action

如果您在两个线程中使用Lock(即读取和写入),读取线程将看到新值,因为monitorEnter会刷新缓存.否则,您需要声明变量volatile以强制在读取线程中从内存读取.

dawei

【声明】:唐山站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。