ReentrantReadWriteLock源码分析
title: JUC.ReentrantReadWriteLock
ReentrantReadWriteLock提纲
ReentrantReadWriteLock简介
ReentrantReadWriteLock适用于读多写少的场景,ReentrantReadWriteLock采用的是读写分离的方式。相比较上一章的StampedLock来说由于没有使用乐观锁的方式,可以保证强一致性。
但是也存在一个问题那就是很有可能会导致写锁饿死。因为有读锁存在则写锁需要等待,有写锁存在则读锁需要等待。上面的StampedLock可以解决这个问题,但是前面也有提到使用的注意规则小心脏数据。
综合来说具体怎么用,用哪种方式还是根据具体的业务场景来判断。没有完美的方案,不然也不会存在两个锁了。接着继续说ReentrantReadWriteLock。
首先看一下类结构图
从类图中可以看出ReentrantReadWriteLock实现了以下锁
1.写锁(独占锁,可以存在非公平与公平两种锁方式)
2.读锁(共享锁,可以存在非公平与公平两种锁方式)
上述就是ReentrantReadWriteLock的大致描述
原理剖析
其实通过上面咱们应该会有以下几个疑问
1.内部如何维护的读写锁分离
2.写锁如何获取以及释放
3.读锁如何获取以及释放
4.当有写锁或者读锁存在,又有线程获取写锁或者读锁怎么处理。
带着上面四个疑问咱们开始看源码。
-
读写分离如何维护
ReentrantReadWriteLock很明显也是通过AQS实现,内部也是通过state维护锁状态。
看源码有下面这一段,高16位表示读锁,低16位表示写锁。读锁总数加重入数65535和写锁可重入最多次数是65535次。
这里真这么多次读锁state的值早超了int最大值。。。。不过影响不大。
static final int SHARED_SHIFT = 16;
//读状态65536
static final int SHARED_UNIT = (1 << SHARED_SHIFT);
//最大读65535
static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1;
//独占锁二进制15个1
static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
-
写锁获取与释放
写锁还是看重写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();
int 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))
return false;
setExclusiveOwnerThread(current);
return true;
}
上述的英文注释写的很明白了三种情况不过多解释。
只说一下CAS这边存在的问题,如果已经有读锁存在则CAS失败进入队列否则成功拿到锁。这里就会很容易导致写锁饿死。。。因为进入队列了。
这里可以设置下公平锁不容易导致写锁饿死。。。这是我能想到的优化方案。
释放锁和以前的套路一样就是在state上面减少1到0了就释放。
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();
if (exclusiveCount(c) != 0 &&
getExclusiveOwnerThread() != current)
return -1;
int r = sharedCount(c);
if (!readerShouldBlock() &&
r < MAX_COUNT &&
compareAndSetState(c, c + SHARED_UNIT)) {
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;
}
return fullTryAcquireShared(current);
}
通过上面代码总结来说其实就是
1.有写锁存在则阻塞进入队列
2.多个线程拿读锁则CAS失败的进入fullTryAcquireShared继续CAS拿锁。
3.通过ThreadLocal记录每个线程重入次数
释放锁代码如下
protected final boolean tryReleaseShared(int unused) {
Thread current = Thread.currentThread();
if (firstReader == current) {
// assert firstReaderHoldCount > 0;
if (firstReaderHoldCount == 1)
firstReader = null;
else
firstReaderHoldCount--;
} 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;
}
for (;;) {
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;
}
}
代码很简单减少当前线程ThreadLocal中的值,然后减少state当0的时候释放锁。
到这咱们上面的问题就都解决完了。
而且到这咱们JAVA中的锁基本都写完了,后面继续写JUC下面的其它工具类。
ThreadLocal的使用后面再写一篇源码分析,线程池里面用这东西还是需要注意下的。
欢迎扫码加入知识星球继续讨论