ReentrantReadWriteLock.Sync::tryReadLock 源码学习

@ReservedStackAccess
final boolean tryReadLock() {
    Thread current = Thread.currentThread();
    // 死循环
    for (;;) {
        int c = getState();
        // 当前有别的线程持有写锁,此时尝试获取读锁失败
        if (exclusiveCount(c) != 0 &&
            getExclusiveOwnerThread() != current)
            return false;
        int r = sharedCount(c);
        // 读锁获取次数已经达到上限,尝试获取读锁失败
        if (r == MAX_COUNT)
            throw new Error("Maximum lock count exceeded");
        // SHARED_UNIT = 1 << 16
        // cas成功说明获取读锁成功
        if (compareAndSetState(c, c + SHARED_UNIT)) {
            if (r == 0) {
                firstReader = current;
                firstReaderHoldCount = 1;
            } else if (firstReader == current) {
                firstReaderHoldCount++;
            } else {
                HoldCounter rh = cachedHoldCounter;
                // 如果当前缓存中保存的HoldCounter不是本线程的,则获取本线程的HoldCounter
                if (rh == null ||
                    rh.tid != LockSupport.getThreadId(current))
                    cachedHoldCounter = rh = readHolds.get();
                // 当rh.count==0时,有可能线程的ThreadLocalMap中已经没有rh这个键
                // 所以为了以防万一,需要重新set一下
                else if (rh.count == 0)
                    readHolds.set(rh);
                rh.count++;
            }
            return true;
        }
    }
}

 

posted @ 2021-05-20 21:01  榆木脑袋0v0  阅读(71)  评论(0)    收藏  举报