Java – does explicit locking automatically provide memory visibility?

Example code:

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;
    }
}

If one thread keeps calling getv and I only execute SETV once in another thread, does the reading thread guarantee to see the new value immediately after writing? Or do you need to change "V" or atomicreference?

If the answer is no, I should change it to:

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;
    }
}

Solution

From documentation:

If you use lock (read and write) in two threads, the read thread will see the new value because monitorenter will flush the cache Otherwise, you need to declare the variable volatile to force a read from memory in the read thread

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>