ReentrantReadWriteLock

Sync


NonfairSync
FairSync

ReadLock
WriteLock

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.)
* 如果计数将饱和,失败。(这只会发生在count已经是非零的情况下。)
* 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;
}
AbstractQueuedSynchronizer


本文详细分析了ReentrantReadWriteLock的实现原理,包括公平锁和非公平锁的tryAcquire方法。在tryAcquire中,检查当前线程是否符合条件获取锁,涉及到了可重入、计数饱和以及线程所有权的判断。同时,介绍了AbstractQueuedSynchronizer在其中的作用,它是Java并发包中的核心抽象类,为锁和其他同步组件提供了基础框架。
1367

被折叠的 条评论
为什么被折叠?



