ReentrantReadWriteLock解析
2018-10-10 本文已影响22人
hvne666
读写锁将状态分为了两部分,高16位表示读,低16位表示写
abstract static class Sync extends AbstractQueuedSynchronizer {
......
static final int SHARED_SHIFT = 16;
static final int SHARED_UNIT = (1 << SHARED_SHIFT);
static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1;
static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
/** Returns the number of shared holds represented in count */
static int sharedCount(int c) { return c >>> SHARED_SHIFT; }
/** Returns the number of exclusive holds represented in count */
static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
1.获取了读锁,不能获取写锁,因为要保证写对读可见
2.获取了写锁,其他线程都被阻塞
protected final boolean tryAcquire(int acquires) {
Thread current = Thread.currentThread();
int c = getState();
int w = exclusiveCount(c); // 写锁状态
if (c != 0) {
// 写 == 0 并且 c != 0 表示 读 != 0,即有读锁时获取不到写锁
// 或者 写 != 0 (有写锁)时但是非本线程,不可以重入
if (w == 0 || current != getExclusiveOwnerThread())
return false;
if (w + exclusiveCount(acquires) > MAX_COUNT)
throw new Error("Maximum lock count exceeded");
setState(c + acquires);
return true;
}
// writerShouldBlock() 公平锁 判断队列前面是否有等待,非公平锁 返回false
if (writerShouldBlock() ||
!compareAndSetState(c, c + acquires))
return false;
setExclusiveOwnerThread(current);
return true;
}