本文需结合读写锁源码 1.8 一起阅读,读写锁的源码需要结合AQS源码一起阅读。
准备
state是一个32位的volatile int。
低16位表示写锁重入次数,高16位表示读锁重入次数
Sync() {
readHolds = new ThreadLocalHoldCounter();
setState(getState()); // ensures visibility of readHolds
}
构造Sync时,这里需要写入state来保证readHolds的可见性
读锁

lock(),unlock(),lockInterruptibly直接调用AQS提供的方法。tryLock()与tryAcquire()几乎一样只是不用考虑公平策略。
读锁需要实现tryAcquire()与tryRelease()。
公平策略的选取
公平策略下,如果排队队列中有前驱节点,那么不会尝试获取而是先进入队列阻塞。
非公平策略下,为了减少写锁的饥饿,如果排队队列的第一个节点是一个写线程,就会先进入队列阻塞(读线程重入除外)。如果写锁没有排在队列中的第一个节点。那么依然有几率导致写锁的饥饿。
获取
public void lock() {
sync.acquireShared(1);
}
来看一下实现的tryAcquireShared(),核心就是CAS改状态,总体流程是比较清楚的,readShouldBolock()这个取决于公平策略的选择。但是一些性能优化的点readHolds,cachedHoldCounter之类刚看可能看不明白,可以先搁置起来结合tryReleaseShared()一起看
性能优化点:
-
firstReader与firstReaderHoldCount用于应付大部分情况下,读锁只会有一个线程获取。然后释放。比用threadlocal类型变量readHolds性能高 -
少部分情况下,不止一个线程获取读锁。那么就用readHolds来存储各个线程读锁的重入次数,这时候依然可以做一些优化,如果释放读锁的线程是刚刚获取读锁的线程。那么为了获取这个线程的重入次数。为了避免用thredlocal,可以设置一个缓存来存储最后一个获取读锁的线程。cachedHoldCounter就是用于缓存最后一个线程的重入次数。
-
2处
if(rh.count == 0) readHolds.set(rh)。原因在于当最后一个获取读锁的线程进行tryRealseShared()的时候如果发现重入次数从1变成0了。那么会从readHolds移除这个HoldCounter。这时候就会存在cachedHoldCounter.count == 0 而该cachedHoldCounter却不存在readHolds中的情况。因此这时候需要set到readHolds中。 -
cahcedHoldCounter并不是volatile变量。他的用意就是让线程缓存在本地变量方便自己查询的。
获取操作,如果资源没有被写锁占有,那么读锁会自旋尝试获取资源,与其他读线程竞争CAS的操作。
protected final int tryAcquireShared(int unused) {
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)) //1
cachedHoldCounter = rh = readHolds.get();
else if (rh.count == 0) //2
readHolds.set(rh);
rh.count++;
}
return 1;
}
return fullTryAcquireShared(current);
}
final int fullTryAcquireShared(Thread current) {
/*
* This code is in part redundant with that in
* tryAcquireShared but is simpler overall by not
* complicating tryAcquireShared with interactions between
* retries and lazily reading hold counts.
*/
HoldCounter rh = null;
for (;;) {
int c = getState();
//如果写锁被占且非重入。失败
if (exclusiveCount(c) != 0) {
if (getExclusiveOwnerThread() != current)
return -1;
// else we hold the exclusive lock; blocking here
// would cause deadlock.
//如果需要阻塞,考察该线程是否是重入获取。若是则失败。
} else if (readerShouldBlock()) {
// Make sure we're not acquiring read lock reentrantly
if (firstReader == current) {
// assert firstReaderHoldCount > 0;
} else {
if (rh == null) {
rh = cachedHoldCounter;
if (rh == null || rh.tid != getThreadId(current)) {
rh = readHolds.get();
if (rh.count == 0)
readHolds.remove();
}
}
if (rh.count == 0)
return -1;
}
}
//到这一步可以进行CAS了。
if (sharedCount(c) == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
if (compareAndSetState(c, c + SHARED_UNIT)) {
if (sharedCount(c) == 0) {
firstReader = current;
firstReaderHoldCount = 1;
} else if (firstReader == current) {
firstReaderHoldCount++;
} else {
if (rh == null)
rh = cachedHoldCounter;
if (rh == null || rh.tid != getThreadId(current))
rh = readHolds.get();
else if (rh.count == 0)
readHolds.set(rh);
rh.count++;
cachedHoldCounter = rh; // cache for release
}
return 1;
}
}
}
释放
返回ture说明此时读锁空闲。
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;
}
}
写锁

公平策略
公平策略下如果有排队的先驱那么就放弃获取,进入排队 非公平策略下 则直接参与锁的竞争
获取
如果读锁已被获取或者写锁线程不是当前线程则失败。
如果是写锁线程重入获取写锁,设置状态不需要用CAS,因为只有当前线程才能设置状态,并发安全。
如果是首个获取写锁的线程(即此时state == 0) 那么需要检查writerShouldBlock,以及设置状态需要用CAS。
写锁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;
}
释放
true表明目前写锁空闲
protected final boolean tryRelease(int releases) {
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
int nextc = getState() - releases;
boolean free = exclusiveCount(nextc) == 0;
if (free)
setExclusiveOwnerThread(null);
setState(nextc);
return free;
}