在查看ReentrantReadWriteLock的官方文档中看到了一个关于锁降级的例子代码:classCachedData{Objectdata;volatilebooleancacheValid;finalReentrantReadWriteLockrwl=newReentrantReadWriteLock();voidprocessCachedData(){rwl.readLock().lock();if(!cacheValid){//Mustreleasereadlockbeforeacquiringwritelockrwl.readLock().unlock();rwl.writeLock().lock();try{//Recheckstatebecauseanotherthreadmighthave//acquiredwritelockandchangedstatebeforewedid.if(!cacheValid){data=...cacheValid=true;}//Downgradebyacquiringreadlockbeforereleasingwritelockrwl.readLock().lock();}finally{rwl.writeLock().unlock();//Unlockwrite,stillholdread}}try{use(data);}finally{rwl.readLock().unlock();}}}这里,在释放写锁前需要先申请读锁,也既锁降级。具体原因是,如果不先获取读锁就释放写锁,那么在执行后面的use(data)时,data有可能被其它线程修改。而由于一个线程对于共享变量的修改对另一个线程来说是不可见的,所以会导致错误。这里,请问,如果我把data变量用volatile修饰,通过volatile来保证可见性的话,是否还需要使用锁降级呢?不知道我对于volatile保证可见性的理解是否正确?
添加回答
举报
0/150
提交
取消