示例代码:
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以强制在读取线程中从内存读取.