ReentrantReadWriteLock学习记录

state的高16位为读锁的线程个数,低16位标识获取写锁的过程中,可重入的次数。

ReadLock和WriteLock是其内部类。

写锁获取

逻辑如下:

        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.)
             * 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) {
                // 下面的判断是读锁存在或者是写锁不是0,且线程不是当前,不可重入,不可获取写锁
                if (w == 0 || current != getExclusiveOwnerThread())
                    return false;
                // 可重入次数超过限制
                if (w + exclusiveCount(acquires) > MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                // 设置当前可重入次数
                setState(c + acquires);
                return true;
            }
            // 获取锁
            if (writerShouldBlock() ||
                !compareAndSetState(c, c + acquires))
                return false;
            // 设置为当前线程获取锁
            setExclusiveOwnerThread(current);
            return true;
        }

读锁获取

其实是获取共享锁

        protected final int tryAcquireShared(int unused) {
            Thread current = Thread.currentThread();
            int c = getState();
            // 写锁存在,且不为当前线程,无法获取锁
            if (exclusiveCount(c) != 0 &&
                getExclusiveOwnerThread() != current)
                return -1;
            int r = sharedCount(c);
            // 读锁线程数小于最大线程,设置成功
            if (!readerShouldBlock() &&
                r < MAX_COUNT &&
                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)
                        readHolds.set(rh);
                    rh.count++;
                }
                return 1;
            }
            return fullTryAcquireShared(current);
        }

你可能感兴趣的:(学习)