一:简介
ReentrantReadWriteLock,读写锁,是对ReentrankLock的改进,通过对读锁与写锁的分离,达到提高性能的目的。比如:在一些业务场景中,大部分只是读数据,写数据很少,如果仅仅是读数据的话并不会影响数据正确性(出现脏读),而如果在这种业务场景下,依然使用独占锁的话,很显然这将是出现性能瓶颈的地方,这个时候就需要用到读写锁了。
读写锁,分为读锁与写锁,因为仅拿读取操作来说不存在线程安全问题,所以同一个时刻可以有多个线程持有读锁,但是因为写操作会改变数据,所以在写线程访问时,所有的持有读锁的线程与其他的写线程都应该阻塞, 即遵循读写互斥,写写互斥原则。
在读写锁中,其特性为以下三个方面:
1:公平性选择,支持非公平(默认)和公平原则
2 : 重进入,该锁支持重进入,在读线程获取读锁后,能再次获取读锁。同样,写线程在获取写锁后也能再次获取写锁。
3:锁降级原则:遵循获取写锁、获取读锁再释放写锁的次序,写锁可以被降级为读锁。
下面就就来具体分析:
二:写锁分析:
2.1写锁的获取
public static class WriteLock implements Lock, java.io.Serializable {...........public void lock() {sync.acquire(1);}.........}
可以发现,仍然是AQS中的模板方法,所以直接分析Sync中的tryAcquire:
protected final boolean tryAcquire(int acquires) {/** Walkthrough:* 1. If read count nonzero or write count nonzero* and owner is a different thread, fail.* 2. If count would saturate, fail. (This can only* happen if count is already nonzero.)* 3. Otherwise, this thread is eligible for lock if* it is either a reentrant acquire or* queue policy allows it. If so, update state* and set owner.*/Thread current = Thread.currentThread();int c = getState(); //获取写锁当前的状态stateint w = exclusiveCount(c); //获取写锁获取的次数if (c != 0) {// (Note: if c != 0 and w == 0 then shared count != 0)//当读锁已经被读线程获取 或者 当前线程不是获取写锁的线程//当前线程获取写锁失败if (w == 0 || current != getExclusiveOwnerThread())return false;if (w + exclusiveCount(acquires) > MAX_COUNT)throw new Error("Maximum lock count exceeded");// Reentrant acquire//当前线程获取写锁,支持可重复加锁setState(c + acquires);return true;}//这个方法是公平与非公平锁的获取判断if (writerShouldBlock() ||!compareAndSetState(c, c + acquires)) //非公平可直接利用CAS获取锁return false;//写锁未被任何线程获取,当前线程可获取写锁setExclusiveOwnerThread(current);return true;}
这段代码的逻辑需要关注几个点;
(1)exclusiveCount(..),其源码为:
/** Returns the number of exclusive holds represented in count */static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }// EXCLUSIVE _MASK为1左移16位然后减1,即为0x0000FFFF。static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
而exclusiveCount方法是将同步状态(state为int类型)与0x0000FFFF相与,即取同步状态的低16位。那么低16位代表什么呢?根据exclusiveCount方法的注释为独占式获取的次数即在这里是写锁被获取的次数,现在就可以得出来一个结论同步状态的低16位用来表示写锁的获取次数。
(2)同时还需要注意一个方法:
/** Returns the number of shared holds represented in count */static int sharedCount(int c) { return c >>> SHARED_SHIFT; }
该方法是获取读锁被获取的次数,是将同步状态(int c)右移16次,即取同步状态的高16位,现在我们可以得出另外一个结论同步状态的高16位用来表示读锁被获取的次数。
即读写锁的读锁和写锁分别记录状态的方式就是state的高十六位(记录读锁状态),低十六位(记录写锁的状态)。
(3)还有一个公平与非公平的判断:
在读写锁中,
static final class FairSync extends Sync {private static final long serialVersionUID = -2274990926593161451L;final boolean writerShouldBlock() {return hasQueuedPredecessors();}final boolean readerShouldBlock() {return hasQueuedPredecessors();}}static final class NonfairSync extends Sync {private static final long serialVersionUID = -8159625535654395037L;final boolean writerShouldBlock() {return false; // writers can always barge}final boolean readerShouldBlock() {return apparentlyFirstQueuedIsExclusive();}}
这里是通过了两个方法即读和写应不应该阻塞的方法的返回值作为公平与非公平的区分,,在上面的tryAcquire(..)中:
//这个方法是公平与非公平锁的获取判断if (writerShouldBlock() ||!compareAndSetState(c, c + acquires)) //非公平可直接利用CAS获取锁return false;
可以看到,非公平还是可直利用CAS获取锁。
现在,总结一下写锁获取方法tryACquire(),其主要的逻辑为,当读锁已经被线程获取或者写锁已经被其他线程获取时,则写锁获取失败(因为读写锁要遵循获取写锁,获取读锁再释放写锁的次序),否则,获取成功并支持重入,增加写状态state中的低16位。
2.2:写锁的释放:
同理,也是通过重写tryRelease方法后,通过调用模板方法release实现的:
protected final boolean tryRelease(int releases) {if (!isHeldExclusively())throw new IllegalMonitorStateException();//同步状态减去写状态int nextc = getState() - releases;//判断写状态(即nextc的低十六位)是否清空为0,为0时释放锁boolean free = exclusiveCount(nextc) == 0;if (free)setExclusiveOwnerThread(null);setState(nextc); //更新statereturn free;}
释放锁的逻辑与ReentrankLock的所释放基本相同,需要注意的是,写状态是用state的低16为保存的,所以在判断free时是在判断nextc的低十六位是否为0.
3:读锁的详情:
因为多个线程均可同时持有读锁,所以读锁不是独占锁,而是共享锁,所以需要重写AQS中的tryAcquireShared方法和tryReleaseShared方法:
protected final int tryAcquireShared(int unused) {/** Walkthrough:* 1. If write lock held by another thread, fail.* 2. Otherwise, this thread is eligible for* lock wrt state, so ask if it should block* because of queue policy. If not, try* to grant by CASing state and updating count.* Note that step does not check for reentrant* acquires, which is postponed to full version* to avoid having to check hold count in* the more typical non-reentrant case.* 3. If step 2 fails either because thread* apparently not eligible or CAS fails or count* saturated, chain to version with full retry loop.*/Thread current = Thread.currentThread();int c = getState(); //获取同步状态//1. 如果写锁已经被获取并且获取写锁的线程不是当前线程的话,当前// 线程获取读锁失败返回-1if (exclusiveCount(c) != 0 &&getExclusiveOwnerThread() != current)return -1;int r = sharedCount(c); //从同步状态中获取共享的次数,上面已经分析过了,state的高16位if (!readerShouldBlock() &&r < MAX_COUNT && //2:当前线程获取读锁compareAndSetState(c, c + SHARED_UNIT)) { //更新state的状态//3. 下面的代码主要是新增的一些功能,比如getReadHoldCount()方法//返回当前获取读锁的次数if (r == 0) {firstReader = current;firstReaderHoldCount = 1;} else if (firstReader == current) {firstReaderHoldCount++;} else {HoldCounter rh = cachedHoldCounter;if (rh == null || rh.tid != getThreadId(current))cachedHoldCounter = rh = readHolds.get();else if (rh.count == 0)readHolds.set(rh);rh.count++;}return 1;}//4. 处理在第二步中CAS操作失败的自旋已经实现读锁的重入性return fullTryAcquireShared(current);}
从代码逻辑中可以看出,当写锁被其他线程获取了就获取读锁失败了(必须遵循获取写锁,获取读锁,释放写锁的原则),否则获取成功后利用CAS更新同步状态。如果CAS失败或者已经获取读锁的线程再次获取读锁时,是靠fullTryAcquireShared方法实现的,具体代码就不贴了,感兴趣了可以看看。
3.2:读锁的释放
protected final boolean tryReleaseShared(int unused) {Thread current = Thread.currentThread();// 前面还是为了实现getReadHoldCount等新功能if (firstReader == current) {// assert firstReaderHoldCount > 0;if (firstReaderHoldCount == 1)firstReader = null;elsefirstReaderHoldCount--;} else {HoldCounter rh = cachedHoldCounter;if (rh == null || rh.tid != getThreadId(current))rh = readHolds.get();int count = rh.count;if (count <= 1) {readHolds.remove();if (count <= 0)throw unmatchedUnlockException();}--rh.count;}//利用自旋,将同步状态减去读状态(高16位)直到为0for (;;) {int c = getState();int nextc = c - SHARED_UNIT;if (compareAndSetState(c, nextc))// Releasing the read lock has no effect on readers,// but it may allow waiting writers to proceed if// both read and write locks are now free.return nextc == 0;}}
读锁的释放就是一个自旋CAS的过程,没有什么特殊的地方。
4:锁的降级(写锁降级为读锁,不支持锁升级)
读写锁支持锁降级,遵循按照获取写锁,获取读锁再释放写锁的次序,写锁能够降级成为读锁,不支持锁升级
例子如下:
void processCachedData() {rwl.readLock().lock();if (!cacheValid) {// Must release read lock before acquiring write lockrwl.readLock().unlock(); //读锁必须先释放rwl.writeLock().lock(); //写锁锁定try {// Recheck state because another thread might have// acquired write lock and changed state before we did.if (!cacheValid) {data = ...cacheValid = true;}// Downgrade by acquiring read lock before releasing write lockrwl.readLock().lock();} finally {rwl.writeLock().unlock(); // Unlock write, still hold read}//锁降级完成,写锁降级为了读锁}try {use(data);} finally {rwl.readLock().unlock();}}}
对于锁降级的解释具体请看并发编程的艺术p145,锁降级即丢掉写锁,只保留读锁。
到这里,我们就分析完了读写锁,对于读写锁,需要记住,写锁是独占锁,读锁是共享锁,注意加锁流程必须是:先获取写锁,然后获取读锁,最后释放写锁,满足这个条件才能获取锁成功,这是本篇的重点,还有一个重点是读锁和写锁的同步状态是根据AQS中state的高16位与低16位分别保存的,记住这个规则才能理解读写锁的可重入与锁的释放。 还有就是利用非公平锁与公平锁类的重写方法返回值才在Sync中实现了非公平与公平锁的区别,至于原理与ReentrankLock没多大区别 。 最后是锁的降级,写锁是可以被降级为读锁的,通过先释放读锁,然后只有一个线程获取写锁,使得其他线程都陷入阻塞,这时再读锁加锁,释放写锁,其他线程就都可以被唤醒获取读锁,这就完成了锁降级,丢掉了写锁,只保留读锁。
