ReentrantReadWriteLock

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

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

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值