/**
* 1、 如果已经有线程获取了读锁,线程A在等待获取写锁,此时线程B将要获取读锁 -- 如果线程B还没获取过读锁,因为有线程A在等待获取
* 写锁,所以会导致线程B阻塞;如果线程B是重入获取读锁,那么可以再次获取读锁,不可以阻塞线程B,一旦阻塞将导致读锁无法完全释放,
* 导致死锁。
*
*/
public class ReentrantReadWriteLock
implements ReadWriteLock, java.io.Serializable {
private static final long serialVersionUID = -6992448646407690164L;
/** Inner class providing readlock */
private final ReentrantReadWriteLock.ReadLock readerLock;
/** Inner class providing writelock */
private final ReentrantReadWriteLock.WriteLock writerLock;
/** Performs all synchronization mechanics */
final Sync sync;
/**
* Creates a new {@code ReentrantReadWriteLock} with
* default (nonfair) ordering properties.
*/
public ReentrantReadWriteLock() {
this(false);
}
/**
* Creates a new {@code ReentrantReadWriteLock} with
* the given fairness policy.
*
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantReadWriteLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
readerLock = new ReadLock(this);
writerLock = new WriteLock(this);
}
public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; }
/**
* Synchronization implementation for ReentrantReadWriteLock.
* Subclassed into fair and nonfair versions.
*/
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 6317671515068378041L;
/*
读取和写入计数提取常数和函数。
* Read vs write count extraction constants and functions.
* Lock state is logically divided into two unsigned shorts:
* The lower one representing the exclusive (writer) lock hold count,
* and the upper the shared (reader) hold count.
*/
// 锁状态在逻辑上分为两个无符号的short:低16位表示独占锁(写锁)保持计数,高16位表示共享锁(读锁)保持计数。
static final int SHARED_SHIFT = 16;
static final int SHARED_UNIT = (1 << SHARED_SHIFT);
static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1;
// 0000 0000 0000 0000 1111 1111 1111 1111
static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
// 返回以count表示的共享持有的数量
/** Returns the number of shared holds represented in count */
// 无符号向右移动16位,表示读取锁的保持计数
static int sharedCount(int c) { return c >>> SHARED_SHIFT; }
// 返回count中表示的独占持有的数量
/** Returns the number of exclusive holds represented in count */
// 清除高16位,保存低16位的值。即写锁保持的计数
static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
/**
* 用于每个线程读取保持计数的计数器。
* A counter for per-thread read hold counts.
* 维护为ThreadLocal;缓存在cachedHoldCounter
* Maintained as a ThreadLocal; cached in cachedHoldCounter
*/
/**
* 记录每个线程获取读取次数的作用是:如果有线程正在等待获取写锁(head的下一个节点是独占模式),
* 如果当前线程没有获取到读锁,那么就不能再去获取读锁,而是进入同步队列,等待写锁获取之后再释放,
* 如果当前线程已经获取过了读锁,即rh.count != 0,那么当前线程还可以再获取读锁而不能阻塞,不然
* 就会造成死锁
*/
static final class HoldCounter {
int count = 0;
// 使用id而不是引用来避免垃圾保留
// Use id, not reference, to avoid garbage retention
final long tid = getThreadId(Thread.currentThread());
}
/**
* 为了反序列化机制,最容易显式定义。
* ThreadLocal subclass. Easiest to explicitly define for sake
* of deserialization mechanics.
*/
static final class ThreadLocalHoldCounter
extends ThreadLocal<HoldCounter> {
public HoldCounter initialValue() {
return new HoldCounter();
}
}
/**
* 当前线程持有的可重入读锁的数量。仅在构造函数和readObject中初始化。
* 当线程的读保持计数下降到0时删除。
* The number of reentrant read locks held by current thread.
* Initialized only in constructor and readObject.
* Removed whenever a thread's read hold count drops to 0.
*/
// new ThreadLocalHoldCounter()
private transient ThreadLocalHoldCounter readHolds;
/**
* 成功获取readLock的最后一个线程的持有计数。在通常情况下,下一个要发布的线程是最后
* 一个要获取的线程,这样做可以节省ThreadLocal查找。这是非volatile的,因为它只是作
* 为一种启发式方法使用,并且对于线程缓存非常有用。
* The hold count of the last thread to successfully acquire
* readLock. This saves ThreadLocal lookup in the common case
* where the next thread to release is the last one to
* acquire. This is non-volatile since it is just used
* as a heuristic, and would be great for threads to cache.
*
* 可以比缓存读保留计数的线程活得更长,但是通过不保留对线程的引用来避免垃圾保留。
* <p>Can outlive the Thread for which it is caching the read
* hold count, but avoids garbage retention by not retaining a
* reference to the Thread.
*
* 通过良性数据竞争访问;依赖于内存模型的最终字段和out- thin-air保证。
* <p>Accessed via a benign data race; relies on the memory
* model's final field and out-of-thin-air guarantees.
*/
// 成功获取readLock的最后一个线程的保存计数。
private transient HoldCounter cachedHoldCounter;
/**
* firstReader 表示获取读锁的第一个线程
* firstReader is the first thread to have acquired the read lock.
*
* firstReaderHoldCount 表示firstReader的保持计数
* firstReaderHoldCount is firstReader's hold count.
*
* 更准确地说,firstReader是惟一的线程,它最后一次将共享计数从0更改为1,
* 并且从那时起就没有释放读锁;如果没有这样的线程,则为空。
* <p>More precisely, firstReader is the unique thread that last
* changed the shared count from 0 to 1, and has not released the
* read lock since then; null if there is no such thread.
*
* 除非线程终止时不释放读锁,否则不会导致垃圾保留,因为tryReleaseShared将其设置为null。
* <p>Cannot cause garbage retention unless the thread terminated
* without relinquishing its read locks, since tryReleaseShared
* sets it to null.
*
* 通过良性数据竞争访问;依赖于内存模型的out- thin-air保证引用。
* <p>Accessed via a benign data race; relies on the memory
* model's out-of-thin-air guarantees for references.
*
* 这使得跟踪非争用读锁的读持有非常便宜。
* <p>This allows tracking of read holds for uncontended read
* locks to be very cheap.
*/
// 获取到读锁的第一个线程
private transient Thread firstReader = null;
// firstReader的保持计数
private transient int firstReaderHoldCount;
Sync() {
readHolds = new ThreadLocalHoldCounter();
// 确保readholds 的可见性 (写 volatile 变量,可以同时把 readHolds 刷新到主存)
setState(getState()); // ensures visibility of readHolds
}
/*
* Acquires and releases use the same code for fair and
* nonfair locks, but differ in whether/how they allow barging
* when queues are non-empty.
*/
/**
* Returns true if the current thread, when trying to acquire
* the read lock, and otherwise eligible to do so, should block
* because of policy for overtaking other waiting threads.
*/
abstract boolean readerShouldBlock();
/**
* Returns true if the current thread, when trying to acquire
* the write lock, and otherwise eligible to do so, should block
* because of policy for overtaking other waiting threads.
*/
abstract boolean writerShouldBlock();
/*
* Note that tryRelease and tryAcquire can be called by
* Conditions. So it is possible that their arguments contain
* both read and write holds that are all released during a
* condition wait and re-established in tryAcquire.
*/
// 写入锁 释放锁调用的是这个方法, 读取锁 释放锁调用的是 tryReleaseShared()方法
protected final boolean tryRelease(int releases) {
// 判断独占锁是否是当前线程获取到的,如果不是抛出异常
if (!isHeldExclusively())
throw new IllegalMonitorStateException();
int nextc = getState() - releases;
// 判断写入锁是否已经完全释放了
boolean free = exclusiveCount(nextc) == 0;
if (free)
// 如果写入锁已经完全释放,设置 exclusiveOwnerThread = null
setExclusiveOwnerThread(null);
// 设置state值,因为当前线程已经获取到了独占锁,所以不需要使用CAS进行操作
setState(nextc);
return free;
}
protected final boolean tryAcquire(int acquires) {
/*
* Walkthrough:
* 如果读取锁保持计数不为0,或者写入锁保持计数不为0,并且锁拥有者是其他线程,则失败
* 1. If read count nonzero or write count nonzero
* and owner is a different thread, fail.
*
* 如果计数超过上限值,则失败 (只会发生在锁保持计数不为0的情况下)
* 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);
// c != 0 说明有线程获取到了写入锁 或者 读取锁
if (c != 0) {
// c != 0 and w == 0 说明有线程获取了 读取锁,此时如果写入锁未被获取 或者 获取写入锁的线程不是当前线程
// 则返回 false
// (Note: if c != 0 and w == 0 then shared count != 0)
if (w == 0 || current != getExclusiveOwnerThread())
return false;
// 执行到这里说明当前线程已经获取到了写入锁,因此不需要使用 CAS 更新 state
if (w + exclusiveCount(acquires) > MAX_COUNT)
throw new Error("Maximum lock count exceeded");
// Reentrant acquire
setState(c + acquires);
return true;
}
// 如果没有线程获取到写入锁 / 读取锁,则执行下面的逻辑
// writerShouldBlock() 非公平锁直接返回false
if (writerShouldBlock() ||
!compareAndSetState(c, c + acquires))
return false;
// 获取写入锁成功,设置 exclusiveOwnerThread 为当前线程
setExclusiveOwnerThread(current);
return true;
}
// 参数 unused 并没有使用
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) {
// 如果此线程已经完全释放锁了,则把 HoldCounter 从线程中移除
readHolds.remove();
if (count <= 0)
throw unmatchedUnlockException();
}
// 线程的读锁保持计数 -1
--rh.count;
}
// CAS循环设置,直到成功为止
for (;;) {
int c = getState();
// state 的读锁保持计数 -1
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;
}
}
private IllegalMonitorStateException unmatchedUnlockException() {
return new IllegalMonitorStateException(
"attempt to unlock read lock, not locked by current thread");
}
// unused 参数没有被使用
protected final int tryAcquireShared(int unused) {
/*
* Walkthrough:
* 1、如果 写锁 被其他线程持有,则失败;
* 1. If write lock held by another thread, fail.
*
* 2、否则,这个线程就符合锁wrt状态的条件,所以请询问它是否应该由于队列策略而阻塞。
* 如果没有,请尝试通过 CAS 修改state 和 更新计数来授予。
* 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.
*
* 注意,这一步不检查可重入获取,它被推迟到完整版本,以避免在更典型的不可重入情况下检查hold 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、如果第2步失败,要么是因为线程显然不符合条件,要么是因为CAS失败或计数饱和,
* 则使用完整的重试循环链接到版本。
* 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();
// 获取 state 值
int c = getState();
// exclusiveCount(c) 获取写锁保持的计数,如果不为0表示 有写锁
if (exclusiveCount(c) != 0 &&
getExclusiveOwnerThread() != current)
// 如果其他线程获取了写锁,那么返回 -1, 表示获取锁失败
return -1;
// 获取读取锁的保持计数
int r = sharedCount(c);
// readerShouldBlock() 判断是否应该阻塞线程,如果head后面的第一个节点是独占模式的(写锁),那么返回true
if (!readerShouldBlock() &&
r < MAX_COUNT && // 保持计数不能超过 65535个
compareAndSetState(c, c + SHARED_UNIT)) { // SHARED_UNIT = (1 << SHARED_SHIFT); 读锁保持计数+1
// 进入到这里表示获取读锁成功
// r == 0 表示,这个线程是第一个获取到读锁的线程
if (r == 0) {
firstReader = current;
firstReaderHoldCount = 1;
} else if (firstReader == current) {
// 如果当前线程是第一个获取到读锁的线程,现在再次获取,firstReaderHoldCount++
firstReaderHoldCount++;
} else {
// cachedHoldCounter 表示成功获取读锁的最后一个线程的保持计数。
HoldCounter rh = cachedHoldCounter;
// 如果 rh.tid != getThreadId(current) 则会重新赋值 cachedHoldCounter
if (rh == null || rh.tid != getThreadId(current))
// readHolds -> ThreadLocalHoldCounter extends ThreadLocal<HoldCounter>
// 如果值为设置,会调用 initialValue()方法进行初始化: new HoldCounter()
// 从线程中获取 (每个线程都保存了该线程获取到读锁的次数)
cachedHoldCounter = rh = readHolds.get();
else if (rh.count == 0)
// 如果 rh.count = 0,说明rh没有保存到 readHolds中
readHolds.set(rh);
// 计数 + 1
// 记录每个线程获取读取次数的作用是:如果有线程正在等待获取写锁(head的下一个节点是独占模式),
// 如果当前线程没有获取到读锁,那么就不能再去获取读锁,而是进入同步队列,等待写锁获取之后再释放,
// 如果当前线程已经获取过了读锁,即rh.count != 0,那么当前线程还可以再获取读锁而不能阻塞,不然
// 就会造成死锁
rh.count++;
}
// 返回1表示获取到锁
return 1;
}
// readerShouldBlock()返回true 或 CAS失败 或 计数饱和(超出最大值了), 将调用这个方法
return fullTryAcquireShared(current);
}
/**
* 读取获取的完整版本,处理CAS失败和可重入读取,tryAcquireShared中没有处理。
* Full version of acquire for reads, that handles CAS misses
* and reentrant reads not dealt with in tryAcquireShared.
*/
final int fullTryAcquireShared(Thread current) {
/*
这段代码与tryacquirered中的代码在一定程度上是冗余的,但总的来说更简单,
因为它没有使tryacquirered在重试和延迟读取hold count之间的交互复杂化。
* 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 (;;) {
// 获取 state 值
int c = getState();
// exclusiveCount(c) 获取写锁保持的计数,如果不为0表示 有写锁
if (exclusiveCount(c) != 0) {
// 如果持有写锁的线程不是当前线程,返回 -1,表示获取锁失败。此时也有可能写锁已经释放了
if (getExclusiveOwnerThread() != current)
return -1;
// 否则我们就持有独占锁;这里的阻塞会导致死锁。 ( 当前线程拥有写锁,如果把当前线程阻塞了,那么久造成死锁了 )
// else we hold the exclusive lock; blocking here
// would cause deadlock.
} else if (readerShouldBlock()) {
// readerShouldBlock() 判断是否应该阻塞线程,如果head后面的第一个节点是独占模式的(写锁),那么返回true
// 若线程应该阻塞,才会进入这里
// 确保我们没有重入获取读锁
// Make sure we're not acquiring read lock reentrantly
// firstReader == current 说明是重入锁。即使有线程在等待获取写锁,但是当前线程已经获取过读锁了,应该要让它
// 可以继续获取读锁,如果阻塞了当前线程,将导致锁不会释放,造成死锁
if (firstReader == current) {
// assert firstReaderHoldCount > 0;
} else {
if (rh == null) {
rh = cachedHoldCounter;
if (rh == null || rh.tid != getThreadId(current)) {
rh = readHolds.get();
// rh.count == 0 表示此线程还未获取过读锁
if (rh.count == 0)
// 删除
readHolds.remove();
}
}
// rh.count == 0 表示当前线程没有获取过读锁,而有线程在等待获取写锁,所以当前线程应该阻塞,
// 避免等待写的线程饥饿
if (rh.count == 0) {
// 返回 -1,说明获取读锁失败
return -1;
}
}
}
// 超出最大获取次数,抛出异常
if (sharedCount(c) == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
// 使用CAS尝试获取锁
if (compareAndSetState(c, c + SHARED_UNIT)) {
// ---- 获取锁成功 ---
// sharedCount(c) == 0 表示,这个线程是第一个获取到读锁的线程
if (sharedCount(c) == 0) {
firstReader = current;
firstReaderHoldCount = 1;
} else if (firstReader == current) {
// 如果当前线程是第一个获取到读锁的线程,现在再次获取,firstReaderHoldCount++
firstReaderHoldCount++;
} else {
if (rh == null)
rh = cachedHoldCounter;
if (rh == null || rh.tid != getThreadId(current))
// 从线程中获取
rh = readHolds.get();
else if (rh.count == 0)
// 如果 rh.count = 0,说明rh没有保存到 ThreadLocal中
readHolds.set(rh);
rh.count++;
// cachedHoldCounter 缓存最后获取读锁的线程的保持计数
cachedHoldCounter = rh; // cache for release
}
// 返回1表示获取到锁
return 1;
}
}
}
/**
* Performs tryLock for write, enabling barging in both modes.
* 除了缺少对writerShouldBlock() 的调用外,这与tryAcquire() 在效果上是相同的。
* This is identical in effect to tryAcquire except for lack
* of calls to writerShouldBlock.
*/
final boolean tryWriteLock() {
Thread current = Thread.currentThread();
int c = getState();
// c != 0 说明有线程获取到了写入锁 / 读取锁
if (c != 0) {
int w = exclusiveCount(c);
// 如果当前线程没有获取到写入锁,则返回 false
// (如果有线程获取到了读取锁/写入锁,如果此时当前线程没有获取到写入锁,则返回false,
// 因此同一个线程如果先获取到了读取锁,则不能再获取到写入锁,但是可以先获取写入锁,再获取读取锁,再获取写入锁)
if (w == 0 || current != getExclusiveOwnerThread())
return false;
// 若超出锁可获取的最大次数,则抛出错误
if (w == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
}
// 使用CAS 获取锁 (此时可能当前线程已经获取到了写入锁,也有可能没有任何线程获取到写入锁,因此需要使用CAS竞争锁)
if (!compareAndSetState(c, c + 1))
return false;
// 获取写入锁成功,设置 exclusiveOwnerThread 为当前线程
setExclusiveOwnerThread(current);
return true;
}
/**
* Performs tryLock for read, enabling barging in both modes.
* 除了缺少对readerShouldBlock()的调用外,这在效果上与tryacquirered()相同。
* This is identical in effect to tryAcquireShared except for
* lack of calls to readerShouldBlock.
*/
final boolean tryReadLock() {
Thread current = Thread.currentThread();
for (;;) {
int c = getState();
// 如果有线程获取了写锁,而且不是由当前线程获取的,则返回 false
if (exclusiveCount(c) != 0 &&
getExclusiveOwnerThread() != current)
return false;
int r = sharedCount(c);
// 如果超过了读锁最大的获取次数,抛出错误
if (r == MAX_COUNT)
throw new Error("Maximum lock count exceeded");
// 如果此时有线程获取到了写锁,那么CAS操作会失败,继续循环的时候就会返回 false
if (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)
// 每当线程获取读锁的保持计数为0 的时候,HoldCounter会从线程中删除,因此当rh.count = 0的
// 时候,需要把 HoldCounter 在放入线程中
readHolds.set(rh);
rh.count++;
}
return true;
}
}
}
// 判断当前线程是否持有写入锁
protected final boolean isHeldExclusively() {
// 虽然我们通常必须在owner之前读取状态(读volatile变量,保持内存一直性),
// 但是我们不需要这样做来检查当前线程是否是owner
// While we must in general read state before owner,
// we don't need to do so to check if current thread is owner
return getExclusiveOwnerThread() == Thread.currentThread();
}
// Methods relayed to outer class
final ConditionObject newCondition() {
return new ConditionObject();
}
final Thread getOwner() {
// 必须先读取状态以确保内存一致性 (先读 volatile变量,exclusiveOwnerThread不是 volatile修饰的)
// Must read state before owner to ensure memory consistency
return ((exclusiveCount(getState()) == 0) ?
null :
getExclusiveOwnerThread());
}
// 获取读锁保持计数
final int getReadLockCount() {
return sharedCount(getState());
}
// 判断写入锁是否被任意线程持有
final boolean isWriteLocked() {
return exclusiveCount(getState()) != 0;
}
final int getWriteHoldCount() {
// 判断当前线程是否拥有锁,若拥有返回写入锁的保持计数,否则返回0
return isHeldExclusively() ? exclusiveCount(getState()) : 0;
}
// 获取当前线程读取锁的保持计数
final int getReadHoldCount() {
if (getReadLockCount() == 0)
return 0;
Thread current = Thread.currentThread();
// 先判断当前线程是否是 firstReader
if (firstReader == current)
return firstReaderHoldCount;
// 接着判断当前线程是否是 cachedHoldCounter缓存的线程
HoldCounter rh = cachedHoldCounter;
if (rh != null && rh.tid == getThreadId(current))
return rh.count;
// 如果都不是,则从 readHolds中获取
int count = readHolds.get().count;
// 因为从readHolds中获取,如果原来的 HoldCounter 不存在,会创建一个,并保存到线程中,
// 如果count = 0,说明此 HoldCounter是新创建的,移除它
if (count == 0) readHolds.remove();
return count;
}
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
readHolds = new ThreadLocalHoldCounter();
setState(0); // reset to unlocked state
}
final int getCount() { return getState(); }
}
// -------------- Sync End -------------------------
/**
* Nonfair version of Sync
*/
static final class NonfairSync extends Sync {
private static final long serialVersionUID = -8159625535654395037L;
final boolean writerShouldBlock() {
// 直接返回false,写入器总是可以获取锁
return false; // writers can always barge
}
// 判断获取读锁的线程是否应该阻塞
final boolean readerShouldBlock() {
/*
* 作为一种避免无限写器饥饿的启发式方法,如果暂时出现队列头的线程(如果存在)是一个
* 正在等待的写器,则阻塞。这只是一种概率效应,因为如果在其他启用的读取器后面有一个
* 等待的写入器,而这些读取器还没有从队列中删除,则新读取器不会阻塞。
* As a heuristic to avoid indefinite writer starvation,
* block if the thread that momentarily appears to be head
* of queue, if one exists, is a waiting writer. This is
* only a probabilistic effect since a new reader will not
* block if there is a waiting writer behind other enabled
* readers that have not yet drained from the queue.
*/
// 这只是一种概率效应, 比如 NodeA -> NodeB -> NodeC, NodeC是一个等待获取写锁的节点,当NodeB获取到锁,
// 然后在设置 HeadB为 head节点之前,有一个新的线程获取读锁,这时候判断的第一个等待的节点还是NodeB,因此新的线程
// 可以去获取锁
// 判断第一个等待的节点(head后面的第一个节点)是否是独占模式的
return apparentlyFirstQueuedIsExclusive();
}
}
/**
* Fair version of Sync
*/
static final class FairSync extends Sync {
private static final long serialVersionUID = -2274990926593161451L;
final boolean writerShouldBlock() {
return hasQueuedPredecessors();
}
final boolean readerShouldBlock() {
return hasQueuedPredecessors();
}
}
/**
* 通过 ReentrantReadWriteLock.readLock() 方法返回的锁
* The lock returned by method {@link ReentrantReadWriteLock#readLock}.
*/
public static class ReadLock implements Lock, java.io.Serializable {
private static final long serialVersionUID = -5992448646407690164L;
private final Sync sync;
/**
* Constructor for use by subclasses
*
* @param lock the outer lock object
* @throws NullPointerException if the lock is null
*/
protected ReadLock(ReentrantReadWriteLock lock) {
sync = lock.sync;
}
/**
* 获取读取锁
* Acquires the read lock.
*
* 如果另一个线程没有保持写入锁,则获取读取锁并立即返回。
* <p>Acquires the read lock if the write lock is not held by
* another thread and returns immediately.
*
* 如果另一个线程保持该写入锁,出于线程调度目的,将禁用当前线程,并且在获取读取锁之前,
* 该线程将一直处于休眠状态。
* <p>If the write lock is held by another thread then
* the current thread becomes disabled for thread scheduling
* purposes and lies dormant until the read lock has been acquired.
*/
public void lock() {
sync.acquireShared(1);
}
/**
* 获取读取锁,除非当前线程被中断。
* Acquires the read lock unless the current thread is
* {@linkplain Thread#interrupt interrupted}.
*
* <p>Acquires the read lock if the write lock is not held
* by another thread and returns immediately.
*
* <p>If the write lock is held by another thread then the
* current thread becomes disabled for thread scheduling
* purposes and lies dormant until one of two things happens:
*
* <ul>
*
* 1、读锁被当前线程获取; 2、其他线程中断了当前线程
* <li>The read lock is acquired by the current thread; or
*
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* the current thread.
*
* </ul>
*
* <p>If the current thread:
*
* <ul>
*
* <li>has its interrupted status set on entry to this method; or
*
* <li>is {@linkplain Thread#interrupt interrupted} while
* acquiring the read lock,
*
* </ul>
*
* 抛出InterruptedException异常,并清算中断状态
* then {@link InterruptedException} is thrown and the current
* thread's interrupted status is cleared.
*
* 在此实现中,因为此方法是一个显式中断点,所以要优先考虑响应中断,而不是响应锁的普通获取或重入获取。
* <p>In this implementation, as this method is an explicit
* interruption point, preference is given to responding to
* the interrupt over normal or reentrant acquisition of the
* lock.
*
* @throws InterruptedException if the current thread is interrupted
*/
public void lockInterruptibly() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
/**
* Acquires the read lock only if the write lock is not held by
* another thread at the time of invocation.
*
* <p>Acquires the read lock if the write lock is not held by
* another thread and returns immediately with the value
* {@code true}. Even when this lock has been set to use a
* fair ordering policy, a call to {@code tryLock()}
* <em>will</em> immediately acquire the read lock if it is
* available, whether or not other threads are currently
* waiting for the read lock. This "barging" behavior
* can be useful in certain circumstances, even though it
* breaks fairness. If you want to honor the fairness setting
* for this lock, then use {@link #tryLock(long, TimeUnit)
* tryLock(0, TimeUnit.SECONDS) } which is almost equivalent
* (it also detects interruption).
*
* <p>If the write lock is held by another thread then
* this method will return immediately with the value
* {@code false}.
*
* @return {@code true} if the read lock was acquired
*/
// 即使是公平锁,此方法也会立即获取锁,而不管等待队列是否有其他线程在等待获取锁
public boolean tryLock() {
return sync.tryReadLock();
}
/**
* 如果其他线程在给定的等待时间内没有保持写入锁,并且当前线程未被中断,则获取读取锁。
* Acquires the read lock if the write lock is not held by
* another thread within the given waiting time and the
* current thread has not been {@linkplain Thread#interrupt
* interrupted}.
*
* <p>Acquires the read lock if the write lock is not held by
* another thread and returns immediately with the value
* 如果已经设置此锁使用公平的排序策略,并且其他线程都在等待该锁,则不会立即获取锁。
* {@code true}. If this lock has been set to use a fair
* ordering policy then an available lock <em>will not</em> be
* acquired if any other threads are waiting for the
* · 这与 tryLock() 方法相反
* lock. This is in contrast to the {@link #tryLock()}
* method. If you want a timed {@code tryLock} that does
* permit barging on a fair lock then combine the timed and
* un-timed forms together:
*
* <pre> {@code
* if (lock.tryLock() ||
* lock.tryLock(timeout, unit)) {
* ...
* }}</pre>
*
* <p>If the write lock is held by another thread then the
* current thread becomes disabled for thread scheduling
* purposes and lies dormant until one of three things happens:
*
* <ul>
*
* 1、读取锁被当前线程获取到
* <li>The read lock is acquired by the current thread; or
*
* 2、其他线程中断了当前线程
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* the current thread; or
*
* 3、等待超时
* <li>The specified waiting time elapses.
*
* </ul>
*
* <p>If the read lock is acquired then the value {@code true} is
* returned.
*
* <p>If the current thread:
*
* <ul>
*
* <li>has its interrupted status set on entry to this method; or
*
* <li>is {@linkplain Thread#interrupt interrupted} while
* acquiring the read lock,
*
* </ul> then {@link InterruptedException} is thrown and the
* current thread's interrupted status is cleared.
*
* 如果超出了指定的等待时间,则返回值为 false。如果该时间小于等于 0,则此方法根本不会等待
* <p>If the specified waiting time elapses then the value
* {@code false} is returned. If the time is less than or
* equal to zero, the method will not wait at all.
*
* <p>In this implementation, as this method is an explicit
* interruption point, preference is given to responding to
* the interrupt over normal or reentrant acquisition of the
* lock, and over reporting the elapse of the waiting time.
*
* @param timeout the time to wait for the read lock
* @param unit the time unit of the timeout argument
* @return {@code true} if the read lock was acquired
* @throws InterruptedException if the current thread is interrupted
* @throws NullPointerException if the time unit is null
*/
// 获取到锁返回true,超时返回false. 且如果是公平锁,则按公平策略获取锁
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
/**
* 释放锁
* Attempts to release this lock.
*
* <p>If the number of readers is now zero then the lock
* is made available for write lock attempts.
*/
public void unlock() {
sync.releaseShared(1);
}
/**
* Throws {@code UnsupportedOperationException} because
* {@code ReadLocks} do not support conditions.
*
* @throws UnsupportedOperationException always
*/
// 不支持使用Condition
public Condition newCondition() {
throw new UnsupportedOperationException();
}
/**
* Returns a string identifying this lock, as well as its lock state.
* 括号中的状态包括字符串{@code "Read locks ="},后面跟着持有的读锁的数量。
* The state, in brackets, includes the String {@code "Read locks ="}
* followed by the number of held read locks.
*
* @return a string identifying this lock, as well as its lock state
*/
public String toString() {
int r = sync.getReadLockCount();
return super.toString() +
"[Read locks = " + r + "]";
}
}
/**
* The lock returned by method {@link ReentrantReadWriteLock#writeLock}.
*/
public static class WriteLock implements Lock, java.io.Serializable {
private static final long serialVersionUID = -4992448646407690164L;
private final Sync sync;
/**
* Constructor for use by subclasses
*
* @param lock the outer lock object
* @throws NullPointerException if the lock is null
*/
protected WriteLock(ReentrantReadWriteLock lock) {
sync = lock.sync;
}
/**
* Acquires the write lock.
*
* 如果另一个线程既没有保持读取锁也没有保持写入锁,则获取写入锁并立即返回,并将写入锁保持计数设置为 1。
* <p>Acquires the write lock if neither the read nor write lock
* are held by another thread
* and returns immediately, setting the write lock hold count to
* one.
*
* 如果当前线程已经保持写入锁,则保持计数增加 1,该方法立即返回。
* <p>If the current thread already holds the write lock then the
* hold count is incremented by one and the method returns
* immediately.
*
* <p>If the lock is held by another thread then the current
* thread becomes disabled for thread scheduling purposes and
* lies dormant until the write lock has been acquired, at which
* time the write lock hold count is set to one.
*/
public void lock() {
// 独占模式获取锁
sync.acquire(1);
}
/**
* 获取写入锁,除非当前线程被中断
* Acquires the write lock unless the current thread is
* {@linkplain Thread#interrupt interrupted}.
*
* 如果其他线程既没有保持读取锁也没有保持写入锁,则获取写入锁并立即返回,并将写入锁保持计数设置为 1。
* <p>Acquires the write lock if neither the read nor write lock
* are held by another thread
* and returns immediately, setting the write lock hold count to
* one.
*
* <p>If the current thread already holds this lock then the
* hold count is incremented by one and the method returns
* immediately.
*
* <p>If the lock is held by another thread then the current
* thread becomes disabled for thread scheduling purposes and
* lies dormant until one of two things happens:
*
* <ul>
*
* 1、写入锁被当前线程获取到
* <li>The write lock is acquired by the current thread; or
*
* 2、其他线程中断了当前线程
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* the current thread.
*
* </ul>
*
* <p>If the write lock is acquired by the current thread then the
* lock hold count is set to one.
*
* <p>If the current thread:
*
* <ul>
*
* <li>has its interrupted status set on entry to this method;
* or
*
* <li>is {@linkplain Thread#interrupt interrupted} while
* acquiring the write lock,
*
* </ul>
*
* 如果当前线程:
* 1、在进入此方法时已经设置了该线程的中断状态;或者
* 2、在获取写入锁时被中断。
* 则抛出 InterruptedException,并且清除当前线程的已中断状态。
* then {@link InterruptedException} is thrown and the current
* thread's interrupted status is cleared.
*
* <p>In this implementation, as this method is an explicit
* interruption point, preference is given to responding to
* the interrupt over normal or reentrant acquisition of the
* lock.
*
* @throws InterruptedException if the current thread is interrupted
*/
// 获取锁,线程被中断时抛出 InterruptedException异常
// (注意:若线程已进入等待队列,则抛出异常是在成功获取到锁之后)
public void lockInterruptibly() throws InterruptedException {
sync.acquireInterruptibly(1);
}
/**
* 仅在方法调用时写入锁没有被其他线程持有时,获取写入锁
* Acquires the write lock only if it is not held by another thread
* at the time of invocation.
*
* <p>Acquires the write lock if neither the read nor write lock
* are held by another thread
* and returns immediately with the value {@code true},
* setting the write lock hold count to one. Even when this lock has
* 即使是公平锁,不管有没有线程在等待获取锁,都会立即竞争锁
* been set to use a fair ordering policy, a call to
* {@code tryLock()} <em>will</em> immediately acquire the
* lock if it is available, whether or not other threads are
* currently waiting for the write lock. This "barging"
* 在某些情况下,此“闯入”行为可能很有用,尽管它打破了公平性
* behavior can be useful in certain circumstances, even
* though it breaks fairness. If you want to honor the
* fairness setting for this lock, then use {@link
* #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
* which is almost equivalent (it also detects interruption).
*
* <p>If the current thread already holds this lock then the
* hold count is incremented by one and the method returns
* {@code true}.
*
* <p>If the lock is held by another thread then this method
* will return immediately with the value {@code false}.
*
* 如果锁是空闲的并且被当前线程获取,或者当前线程已经保持写入锁,则返回 true;否则返回 false。
* @return {@code true} if the lock was free and was acquired
* by the current thread, or the write lock was already held
* by the current thread; and {@code false} otherwise.
*/
public boolean tryLock( ) {
return sync.tryWriteLock();
}
/**
* 在给定的时间内线程没有被中断,且写入锁没有被其他线程持有,则获取写入锁
* Acquires the write lock if it is not held by another thread
* within the given waiting time and the current thread has
* not been {@linkplain Thread#interrupt interrupted}.
*
* <p>Acquires the write lock if neither the read nor write lock
* are held by another thread
* and returns immediately with the value {@code true},
* setting the write lock hold count to one. If this lock has been
* 如果是公平锁,则会遵守公平锁规则
* set to use a fair ordering policy then an available lock
* <em>will not</em> be acquired if any other threads are
* waiting for the write lock. This is in contrast to the {@link
* #tryLock()} method. If you want a timed {@code tryLock}
* 如果想使用一个允许闯入公平锁的定时 tryLock,那么可以将定时形式和不定时形式组合在一起:
* that does permit barging on a fair lock then combine the
* timed and un-timed forms together:
*
* <pre> {@code
* if (lock.tryLock() ||
* lock.tryLock(timeout, unit)) {
* ...
* }}</pre>
*
* <p>If the current thread already holds this lock then the
* hold count is incremented by one and the method returns
* {@code true}.
*
* <p>If the lock is held by another thread then the current
* thread becomes disabled for thread scheduling purposes and
* lies dormant until one of three things happens:
*
* <ul>
*
* 1、写入锁被当前线程获取到
* <li>The write lock is acquired by the current thread; or
*
* 2、其他线程中断了当前线程
* <li>Some other thread {@linkplain Thread#interrupt interrupts}
* the current thread; or
*
* 3、等待超时
* <li>The specified waiting time elapses
*
* </ul>
*
* 如果写入锁被获取,则返回true,并且写入锁保持计数设置为1
* <p>If the write lock is acquired then the value {@code true} is
* returned and the write lock hold count is set to one.
*
* <p>If the current thread:
*
* <ul>
*
* <li>has its interrupted status set on entry to this method;
* or
*
* <li>is {@linkplain Thread#interrupt interrupted} while
* acquiring the write lock,
*
* </ul>
*
* then {@link InterruptedException} is thrown and the current
* thread's interrupted status is cleared.
*
* 如果等待超时,返回false. 如果该时间小于等于 0,则此方法根本不会等待。
* <p>If the specified waiting time elapses then the value
* {@code false} is returned. If the time is less than or
* equal to zero, the method will not wait at all.
*
* <p>In this implementation, as this method is an explicit
* interruption point, preference is given to responding to
* the interrupt over normal or reentrant acquisition of the
* lock, and over reporting the elapse of the waiting time.
*
* @param timeout the time to wait for the write lock
* @param unit the time unit of the timeout argument
*
* 如果锁是空闲的并且由当前线程获取,或者当前线程已经保持写入锁,则返回 true;
* 如果在获取该锁之前已经到达等待时间,则返回 false。
* @return {@code true} if the lock was free and was acquired
* by the current thread, or the write lock was already held by the
* current thread; and {@code false} if the waiting time
* elapsed before the lock could be acquired.
*
* @throws InterruptedException if the current thread is interrupted
* @throws NullPointerException if the time unit is null
*/
public boolean tryLock(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireNanos(1, unit.toNanos(timeout));
}
/**
* Attempts to release this lock.
*
* <p>If the current thread is the holder of this lock then
* the hold count is decremented. If the hold count is now
* zero then the lock is released. If the current thread is
* not the holder of this lock then {@link
* IllegalMonitorStateException} is thrown.
*
* @throws IllegalMonitorStateException if the current thread does not
* hold this lock
*/
public void unlock() {
// 独占模式释放锁
sync.release(1);
}
/**
* Returns a {@link Condition} instance for use with this
* {@link Lock} instance.
* <p>The returned {@link Condition} instance supports the same
* usages as do the {@link Object} monitor methods ({@link
* Object#wait() wait}, {@link Object#notify notify}, and {@link
* Object#notifyAll notifyAll}) when used with the built-in
* monitor lock.
*
* <ul>
*
* <li>If this write lock is not held when any {@link
* Condition} method is called then an {@link
* IllegalMonitorStateException} is thrown. (Read locks are
* (因为保持读取锁是独立于写入锁的,所以读取锁将不被检查或受影响。但是,
* 在当前线程已经获取读取锁时,调用一个条件等待方法实质上一直是错误的做法,
* 因为能够解除阻塞该方法的其他线程将无法获取写入锁。)
* held independently of write locks, so are not checked or
* affected. However it is essentially always an error to
* invoke a condition waiting method when the current thread
* has also acquired read locks, since other threads that
* could unblock it will not be able to acquire the write
* lock.)
*
* 当调用等待条件方法并释放写入锁时,在它们返回之前,会重新获取写入锁,并将锁保持计数恢复到调用该方法时的值。
* <li>When the condition {@linkplain Condition#await() waiting}
* methods are called the write lock is released and, before
* they return, the write lock is reacquired and the lock hold
* count restored to what it was when the method was called.
*
* 如果线程在等待时被中断,则等待将终止,并将抛出 InterruptedException,清除线程的已中断状态。
* <li>If a thread is {@linkplain Thread#interrupt interrupted} while
* waiting then the wait will terminate, an {@link
* InterruptedException} will be thrown, and the thread's
* interrupted status will be cleared.
*
* 等待线程按 FIFO 顺序收到信号。
* <li> Waiting threads are signalled in FIFO order.
*
* 等待方法返回的线程重新获取锁的顺序与线程最初获取锁的顺序相同,在默认情况下,
* 未指定此顺序,但对于公平 锁,它们更倾向于那些等待时间最长的线程。
* <li>The ordering of lock reacquisition for threads returning
* from waiting methods is the same as for threads initially
* acquiring the lock, which is in the default case not specified,
* but for <em>fair</em> locks favors those threads that have been
* waiting the longest.
*
* </ul>
*
* @return the Condition object
*/
public Condition newCondition() {
return sync.newCondition();
}
/**
* Returns a string identifying this lock, as well as its lock
* state. The state, in brackets includes either the String
* {@code "Unlocked"} or the String {@code "Locked by"}
* followed by the {@linkplain Thread#getName name} of the owning thread.
*
* @return a string identifying this lock, as well as its lock state
*/
public String toString() {
Thread o = sync.getOwner();
return super.toString() + ((o == null) ?
"[Unlocked]" :
"[Locked by thread " + o.getName() + "]");
}
/**
* 查询写入锁是否由当前线程持有
* Queries if this write lock is held by the current thread.
* 与 ReentrantReadWriteLock.isWriteLockedByCurrentThread() 效果相同。
* Identical in effect to {@link
* ReentrantReadWriteLock#isWriteLockedByCurrentThread}.
*
* @return {@code true} if the current thread holds this lock and
* {@code false} otherwise
* @since 1.6
*/
// 如果当前线程持有写入锁,返回true,否则返回 false
public boolean isHeldByCurrentThread() {
return sync.isHeldExclusively();
}
/**
* 查询当前线程保持写入锁的数量。对于与解锁操作不匹配的每个锁操作,线程都会为其保持一个锁。
* 与 ReentrantReadWriteLock.getWriteHoldCount() 效果相同。
* Queries the number of holds on this write lock by the current
* thread. A thread has a hold on a lock for each lock action
* that is not matched by an unlock action. Identical in effect
* to {@link ReentrantReadWriteLock#getWriteHoldCount}.
*
* @return the number of holds on this lock by the current thread,
* or zero if this lock is not held by the current thread
* @since 1.6
*/
// 获取当前线程保持写入锁的数量,若当前线程没有获得写入锁,返回0
public int getHoldCount() {
return sync.getWriteHoldCount();
}
}
// Instrumentation and status
/**
* Returns {@code true} if this lock has fairness set true.
*
* @return {@code true} if this lock has fairness set true
*/
// 判断是否是公平锁,是返回 true, 否则返回 false
public final boolean isFair() {
return sync instanceof FairSync;
}
/**
* 返回当前持有写入锁的线程,若写入锁没有被获取,返回null
* Returns the thread that currently owns the write lock, or
* {@code null} if not owned.
* 当通过不是所有者的线程调用此方法时,返回值反映当前锁状态的最接近近似值。
* 例如,即使存在试图获得锁的线程,但是在它还没有获得前,所有者可能暂时为 null。
* When this method is called by a
* thread that is not the owner, the return value reflects a
* best-effort approximation of current lock status. For example,
* the owner may be momentarily {@code null} even if there are
* threads trying to acquire the lock but have not yet done so.
* This method is designed to facilitate construction of
* subclasses that provide more extensive lock monitoring
* facilities.
*
* @return the owner, or {@code null} if not owned
*/
protected Thread getOwner() {
return sync.getOwner();
}
/**
* 查询为此锁保持的读取锁数量。此方法设计用于监视系统状态,而不是同步控制。
* Queries the number of read locks held for this lock. This
* method is designed for use in monitoring system state, not for
* synchronization control.
* @return the number of read locks held
*/
public int getReadLockCount() {
return sync.getReadLockCount();
}
/**
* 查询写入锁是否被任意线程持有
* Queries if the write lock is held by any thread. This method is
* designed for use in monitoring system state, not for
* synchronization control.
*
* @return {@code true} if any thread holds the write lock and
* {@code false} otherwise
*/
public boolean isWriteLocked() {
return sync.isWriteLocked();
}
/**
* 查询当前线程是否持有写入锁
* Queries if the write lock is held by the current thread.
*
* 若当前线程持有写入锁,返回true,否则返回false
* @return {@code true} if the current thread holds the write lock and
* {@code false} otherwise
*/
public boolean isWriteLockedByCurrentThread() {
return sync.isHeldExclusively();
}
/**
* 查询当前线程在此锁上保持的重入写入锁数量。
* Queries the number of reentrant write holds on this lock by the
* 对于与解除锁操作不匹配的每个锁操作,writer 线程都会为其保持一个锁。
* current thread. A writer thread has a hold on a lock for
* each lock action that is not matched by an unlock action.
*
* @return the number of holds on the write lock by the current thread,
* or zero if the write lock is not held by the current thread
*/
// 返回当前线程保持的写入锁数量,如果当前线程从未保持过写入锁,则返回 0
public int getWriteHoldCount() {
return sync.getWriteHoldCount();
}
/**
* 查询当前线程在此锁上保持的重入读取锁数量。对于与解除锁操作不匹配的每个锁操作,
* reader 线程都会为其保持一个锁。
* Queries the number of reentrant read holds on this lock by the
* current thread. A reader thread has a hold on a lock for
* each lock action that is not matched by an unlock action.
*
* @return the number of holds on the read lock by the current thread,
* or zero if the read lock is not held by the current thread
* @since 1.6
*/
// 返回当前线程保持的读取锁数量;如果当前线程从未保持过读取锁,则返回 0
public int getReadHoldCount() {
return sync.getReadHoldCount();
}
/**
* 返回一个 collection,它包含可能正在等待获取写入锁的线程。因为在构成此结果的同时,
* 实际的线程 set 可能不断发生变化,所以返回的 collection 仅是尽力而为获得的估计值。
* 所返回 collection 的元素没有特定的顺序。设计此方法是为了便于构造提供更多扩展的锁监视器设施的子类。
* Returns a collection containing threads that may be waiting to
* acquire the write lock. Because the actual set of threads may
* change dynamically while constructing this result, the returned
* collection is only a best-effort estimate. The elements of the
* returned collection are in no particular order. This method is
* designed to facilitate construction of subclasses that provide
* more extensive lock monitoring facilities.
*
* @return the collection of threads
*/
// 获取同步队列中所有独占模式的线程集合(包含head节点,即已经获取到锁的线程)
protected Collection<Thread> getQueuedWriterThreads() {
return sync.getExclusiveQueuedThreads();
}
/**
* 返回一个 collection,它包含可能正在等待获取读取锁的线程。
* Returns a collection containing threads that may be waiting to
* acquire the read lock. Because the actual set of threads may
* change dynamically while constructing this result, the returned
* collection is only a best-effort estimate. The elements of the
* returned collection are in no particular order. This method is
* designed to facilitate construction of subclasses that provide
* more extensive lock monitoring facilities.
*
* @return the collection of threads
*/
// 获取同步队列中所有共享模式的线程集合(包含head节点,即已经获取到锁的线程)
protected Collection<Thread> getQueuedReaderThreads() {
return sync.getSharedQueuedThreads();
}
/**
* 查询是否有线程正在等待获取读取或写入锁。注意,因为随时可能发生取消操作,
* 所以返回 true 并不保证任何其他线程将获取锁。此方法主要用于监视系统状态。
* Queries whether any threads are waiting to acquire the read or
* write lock. Note that because cancellations may occur at any
* time, a {@code true} return does not guarantee that any other
* thread will ever acquire a lock. This method is designed
* primarily for use in monitoring of the system state.
*
* @return {@code true} if there may be other threads waiting to
* acquire the lock
*/
// 判断是否有线程在等待获取锁 (不包含已经获取到锁的head节点)
public final boolean hasQueuedThreads() {
return sync.hasQueuedThreads();
}
/**
* 查询是否给定线程正在等待获取读取或写入锁。
* Queries whether the given thread is waiting to acquire either
* the read or write lock. Note that because cancellations may
* occur at any time, a {@code true} return does not guarantee
* that this thread will ever acquire a lock. This method is
* designed primarily for use in monitoring of the system state.
*
* @param thread the thread
* @return {@code true} if the given thread is queued waiting for this lock
* @throws NullPointerException if the thread is null
*/
public final boolean hasQueuedThread(Thread thread) {
return sync.isQueued(thread);
}
/**
* 返回等待获取读取或写入锁的线程估计数目
* Returns an estimate of the number of threads waiting to acquire
* either the read or write lock. The value is only an estimate
* because the number of threads may change dynamically while this
* method traverses internal data structures. This method is
* designed for use in monitoring of the system state, not for
* synchronization control.
*
* @return the estimated number of threads waiting for this lock
*/
public final int getQueueLength() {
return sync.getQueueLength();
}
/**
* 返回一个 collection,它包含可能正在等待获取读取或写入锁的线程。
* Returns a collection containing threads that may be waiting to
* acquire either the read or write lock. Because the actual set
* of threads may change dynamically while constructing this
* result, the returned collection is only a best-effort estimate.
* The elements of the returned collection are in no particular
* order. This method is designed to facilitate construction of
* subclasses that provide more extensive monitoring facilities.
*
* @return the collection of threads
*/
protected Collection<Thread> getQueuedThreads() {
return sync.getQueuedThreads();
}
/**
* 查询是否有些线程正在等待与写入锁有关的给定condition。
* Queries whether any threads are waiting on the given condition
* associated with the write lock. Note that because timeouts and
* interrupts may occur at any time, a {@code true} return does
* not guarantee that a future {@code signal} will awaken any
* threads. This method is designed primarily for use in
* monitoring of the system state.
*
* @param condition the condition
* @return {@code true} if there are any waiting threads
* @throws IllegalMonitorStateException if this lock is not held
* @throws IllegalArgumentException if the given condition is
* not associated with this lock
* @throws NullPointerException if the condition is null
*/
public boolean hasWaiters(Condition condition) {
if (condition == null)
throw new NullPointerException();
if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
throw new IllegalArgumentException("not owner");
return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
}
/**
* 返回正等待与写入锁相关的给定条件的线程估计数目。
* Returns an estimate of the number of threads waiting on the
* given condition associated with the write lock. Note that because
* timeouts and interrupts may occur at any time, the estimate
* serves only as an upper bound on the actual number of waiters.
* This method is designed for use in monitoring of the system
* state, not for synchronization control.
*
* @param condition the condition
* @return the estimated number of waiting threads
* @throws IllegalMonitorStateException if this lock is not held
* @throws IllegalArgumentException if the given condition is
* not associated with this lock
* @throws NullPointerException if the condition is null
*/
public int getWaitQueueLength(Condition condition) {
if (condition == null)
throw new NullPointerException();
if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
throw new IllegalArgumentException("not owner");
return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
}
/**
* 返回一个 collection,它包含可能正在等待与写入锁相关的给定条件的那些线程。
* Returns a collection containing those threads that may be
* waiting on the given condition associated with the write lock.
* Because the actual set of threads may change dynamically while
* constructing this result, the returned collection is only a
* best-effort estimate. The elements of the returned collection
* are in no particular order. This method is designed to
* facilitate construction of subclasses that provide more
* extensive condition monitoring facilities.
*
* @param condition the condition
* @return the collection of threads
* @throws IllegalMonitorStateException if this lock is not held
* @throws IllegalArgumentException if the given condition is
* not associated with this lock
* @throws NullPointerException if the condition is null
*/
protected Collection<Thread> getWaitingThreads(Condition condition) {
if (condition == null)
throw new NullPointerException();
if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
throw new IllegalArgumentException("not owner");
return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
}
/**
* Returns a string identifying this lock, as well as its lock state.
* The state, in brackets, includes the String {@code "Write locks ="}
* followed by the number of reentrantly held write locks, and the
* String {@code "Read locks ="} followed by the number of held
* read locks.
*
* @return a string identifying this lock, as well as its lock state
*/
public String toString() {
int c = sync.getCount();
int w = Sync.exclusiveCount(c);
int r = Sync.sharedCount(c);
return super.toString() +
"[Write locks = " + w + ", Read locks = " + r + "]";
}
/**
* Returns the thread id for the given thread. We must access
* this directly rather than via method Thread.getId() because
* getId() is not final, and has been known to be overridden in
* ways that do not preserve unique mappings.
*/
static final long getThreadId(Thread thread) {
return UNSAFE.getLongVolatile(thread, TID_OFFSET);
}
// Unsafe mechanics
private static final sun.misc.Unsafe UNSAFE;
private static final long TID_OFFSET;
static {
try {
UNSAFE = sun.misc.Unsafe.getUnsafe();
Class<?> tk = Thread.class;
TID_OFFSET = UNSAFE.objectFieldOffset
(tk.getDeclaredField("tid"));
} catch (Exception e) {
throw new Error(e);
}
}
}