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