Java读写锁降级

import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class LockDownGrade { private final ReentrantReadWriteLock readWriteLock; private final Lock readLock; private final Lock writeLock; private volatile boolean updateFlag; public LockDownGrade() { this.readWriteLock = new ReentrantReadWriteLock(); this.writeLock = readWriteLock.writeLock(); this.readLock = readWriteLock.readLock(); } public void processData(){ final Lock localReadLock = this.readLock; //读锁获取 localReadLock.lock();//读锁获取 if (!updateFlag) { readLock.unlock();//必须先释放读锁 //锁降级从获取写锁开始 writeLock.lock(); try { if (!updateFlag) { //TODO 准备数据流程 updateFlag = true; } //获取读锁。在写锁持有期间获取读锁 //此处获取读锁,是为了防止,当释放写锁后,又有一个线程T获取锁,对数据进行改变,而当前线程下面对改变的数据无法感知。 //如果获取了读锁,则线程T则被阻塞,直到当前线程释放了读锁,那个T线程才有可能获取写锁。 readLock.lock(); } finally { //释放写锁 writeLock.unlock(); } //锁降级完成 try { //TODO 使用数据的流程 } finally { //释放读锁 readLock.unlock(); } } } }

点赞