源码分析--ReentrantReadWriteLock(一)

16 篇文章 0 订阅

概述

ReentrantReadWriteLock 是读写锁,它维护了一对锁:一个读锁,一个写锁。读锁之间是共享的,写锁是互斥的。与 ReentrantLock 相比,读写锁在读多写少的场景下允许更高的并发量。

类图如下:

在这里插入图片描述
ReentrantReadWriteLock中的类分成三个部分:
(1)ReentrantReadWriteLock本身实现了ReadWriteLock接口,这个接口只提供了两个方法readLock()和writeLock();
(2)同步器,包含一个继承了AQS的Sync内部类,以及其两个子类FairSync和NonfairSync;
(3)ReadLock和WriteLock两个内部类实现了Lock接口,它们具有锁的一些特性。

源码分析

构造方法:

// 默认构造方法
public ReentrantReadWriteLock() {
    this(false);
}
// 是否使用公平锁的构造方法
public ReentrantReadWriteLock(boolean fair) {
    sync = fair ? new FairSync() : new NonfairSync();
    readerLock = new ReadLock(this);
    writerLock = new WriteLock(this);
}

与 ReentrantLock 类似,这里的构造器也传入了公平策略,且默认为非公平。构造器内部初始化了三个变量:sync、readerLock 和 writerLock,如下:

// 提供读锁的内部类
private final ReentrantReadWriteLock.ReadLock readerLock;

// 提供写锁的内部类
private final ReentrantReadWriteLock.WriteLock writerLock;

// 执行所有的同步机制
final Sync sync;

内部类Sync:
Sync 类继承自 AQS(与 ReentrantLock 中的 Sync 类似),如下:

abstract static class Sync extends AbstractQueuedSynchronizer {
    // 使用 AQS 中的 state 变量(int 类型)来记录读写锁的占用情况
    // 其中高 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;
    static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;

    // 共享锁(读锁)的持有次数
    static int sharedCount(int c)    { return c >>> SHARED_SHIFT; }
    // 互斥锁(写锁)的重入次数
    static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }

    /**
     * 每个线程持有读锁的计数器。
     * 以 ThreadLocal 形式保存,缓存在 cachedHoldCounter
     * 该类的主要作用是记录线程持有读锁的数量,可理解为 <tid,count> 的形式
     */    
    static final class HoldCounter {
        int count = 0;
        // Use id, not reference, to avoid garbage retention
        final long tid = getThreadId(Thread.currentThread());
    }

    static final class ThreadLocalHoldCounter
        extends ThreadLocal<HoldCounter> {
        public HoldCounter initialValue() {
            return new HoldCounter();
        }
    }

    /**
     * 当前线程持有的可重入读锁的数量(数量为0时删除)。
     */
    private transient ThreadLocalHoldCounter readHolds;

    private transient HoldCounter cachedHoldCounter;

    /**
     * firstReader:第一个获取读锁的线程;
     * firstReaderHoldCount:firstReader 的持有计数。
     */
    private transient Thread firstReader = null;
    private transient int firstReaderHoldCount;

    Sync() {
        readHolds = new ThreadLocalHoldCounter();
        setState(getState()); // ensures visibility of readHolds
    }

    /*
     * 对于公平锁和非公平锁,获取和释放锁使用的代码相同;
     * 但在队列非空时,它们是否或如何允许插入的方式不同。
     */

    /**
     * 当前线程在尝试(或有资格)获取读锁时,是否应该由于策略原因而阻塞。
     */
    abstract boolean readerShouldBlock();

    /**
     * 当前线程在尝试(或有资格)获取写锁时,是否应该由于策略原因而阻塞。
     */
    abstract boolean writerShouldBlock();

    // 释放写锁
    protected final boolean tryRelease(int releases) {
        if (!isHeldExclusively())
            throw new IllegalMonitorStateException();
        int nextc = getState() - releases;
        boolean free = exclusiveCount(nextc) == 0;
        if (free)
            setExclusiveOwnerThread(null);
        setState(nextc);
        return free;
    }

    // 获取写锁
    protected final boolean tryAcquire(int acquires) {
        /*
         * 流程:
         * 1. 若其他线程持有读锁或写锁(计数不为零),返回 false;
         * 2. 若持有数量饱和(超出上限),返回 false;
         * 3. 该线程有资格获取锁,更新 state 并设置为 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;
        }
        // 若获取写锁时应该阻塞,或者更新 state 失败,返回 false
        if (writerShouldBlock() ||
            !compareAndSetState(c, c + acquires))
            return false;
        setExclusiveOwnerThread(current);
        return true;
    }

    // 释放读锁
    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) {
                readHolds.remove();
                if (count <= 0)
                    throw unmatchedUnlockException();
            }
            --rh.count;
        }
        // 更新 state
        for (;;) {
            int c = getState();
            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;
        }
    }

    // 获取读锁
    protected final int tryAcquireShared(int unused) {
        /*
         * 流程:
         * 1. 如果其他线程持有写锁,获取失败;
         * 2. 否则,该线程有资格获取,因此请询问它是否由于队列策略而阻塞;
         *    若不阻塞,尝试通过 CAS 更新状态计数。
         *    注意:这一步没有检查可重入的获取,推迟到完整版本,
         *         以避免在明显不可重入的情况下检查持有计数。
         * 3. 如果第二步失败,要么是因为线程明显不符合条件、CAS 失败或计数饱和,
         *    则进行完整重试版本。
         */
        Thread current = Thread.currentThread();
        int c = getState();
        // step1. 若写锁被其他线程占用,则获取失败
        //        exclusiveCount(c) != 0表示写锁被占用
        if (exclusiveCount(c) != 0 &&
            getExclusiveOwnerThread() != current)
            return -1;
        // step2. 获取读锁数量
        int r = sharedCount(c);
        if (!readerShouldBlock() &&
            r < MAX_COUNT &&
            compareAndSetState(c, c + SHARED_UNIT)) {
            // 读锁未被占用,设置该线程是第一个持有读锁的线程
            if (r == 0) {
                firstReader = current;
                firstReaderHoldCount = 1;
            // 该线程已持有读锁,计数加1
            } else if (firstReader == current) {
                firstReaderHoldCount++;
            // 其他线程已持有读锁
            } else {
                // 取缓存
                HoldCounter rh = cachedHoldCounter;
                // 若未初始化,或者拿到的不是当前线程的计数,则从 ThreadLocal 中获取
                if (rh == null || rh.tid != getThreadId(current))
                    cachedHoldCounter = rh = readHolds.get();
                else if (rh.count == 0)
                    readHolds.set(rh);
                // 增加计数
                rh.count++;
            }
            // 获取成功
            return 1;
        }
        // step3. 若step2获取失败,则执行该步骤
        return fullTryAcquireShared(current);
    }

    /**
     * 获取读锁的完整版,处理 tryAcquireShared 中未处理的 CAS 丢失和可重入读取。
     */
    final int fullTryAcquireShared(Thread current) {
        HoldCounter rh = null;
        for (;;) {
            int c = getState();
            // 如果其他线程占用写锁,获取失败
            if (exclusiveCount(c) != 0) {
                if (getExclusiveOwnerThread() != current)
                    return -1;
                // else we hold the exclusive lock; blocking here
                // would cause deadlock.
            } else if (readerShouldBlock()) {
                // Make sure we're not acquiring read lock reentrantly
                if (firstReader == current) {
                    // assert firstReaderHoldCount > 0;
                } else {
                    if (rh == null) {
                        rh = cachedHoldCounter;
                        if (rh == null || rh.tid != getThreadId(current)) {
                            rh = readHolds.get();
                            if (rh.count == 0)
                                readHolds.remove();
                        }
                    }
                    if (rh.count == 0)
                        return -1;
                }
            }
            if (sharedCount(c) == MAX_COUNT)
                throw new Error("Maximum lock count exceeded");
            if (compareAndSetState(c, c + SHARED_UNIT)) {
                if (sharedCount(c) == 0) {
                    firstReader = current;
                    firstReaderHoldCount = 1;
                } else if (firstReader == current) {
                    firstReaderHoldCount++;
                } else {
                    if (rh == null)
                        rh = cachedHoldCounter;
                    if (rh == null || rh.tid != getThreadId(current))
                        rh = readHolds.get();
                    else if (rh.count == 0)
                        readHolds.set(rh);
                    rh.count++;
                    cachedHoldCounter = rh; // cache for release
                }
                return 1;
            }
        }
    }

    /**
     * 执行写锁的 tryLock 方法
     * 与 tryAcquire 相比,该方法未调用 writerShouldBlock
     */
    final boolean tryWriteLock() {
        Thread current = Thread.currentThread();
        int c = getState();
        if (c != 0) {
            int w = exclusiveCount(c);
            if (w == 0 || current != getExclusiveOwnerThread())
                return false;
            if (w == MAX_COUNT)
                throw new Error("Maximum lock count exceeded");
        }
        if (!compareAndSetState(c, c + 1))
            return false;
        setExclusiveOwnerThread(current);
        return true;
    }

    /**
     * 执行读锁的 tryLock 方法
     * 与 tryAcquireShared 相比,该方法未调用 readerShouldBlock
     */
    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");
            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)
                        readHolds.set(rh);
                    rh.count++;
                }
                return true;
            }
        }
    }
}

在这里插入图片描述
内部类NonfairSync :
NonfairSync 继承自 Sync 类,提供非公平策略的实现,如下:

static final class NonfairSync extends Sync {
    final boolean writerShouldBlock() {
        return false; // writers can always barge
    }
    final boolean readerShouldBlock() {
        // 调用父类 AQS 中的方法实现
        return apparentlyFirstQueuedIsExclusive();
    }
}

// 若头节点的下一个节点是写线程,为了防止写线程饥饿等待,当前的读线程应该阻塞
final boolean apparentlyFirstQueuedIsExclusive() {
    Node h, s;
    return (h = head) != null &&
        (s = h.next)  != null &&
        !s.isShared()         &&
        s.thread != null;
}

非公平策略中,writerShouldBlock 返回 false,说明写线程无需阻塞;

readerShouldBlock 则是调用父类 AQS 中的 apparentlyFirstQueuedIsExclusive 方法实现的,该方法通过判断等待队列中的第一个线程是否为写线程,若是则返回 true,表示给写线程让道。

内部类FairSync:

static final class FairSync extends Sync {
    final boolean writerShouldBlock() {
        return hasQueuedPredecessors();
    }
    final boolean readerShouldBlock() {
        return hasQueuedPredecessors();
    }
}

在公平策略中,两个方法都通过调用父类 AQS 的 hasQueuedPredecessors 方法判别,二者都是根据等待队列中是否有其他线程,若有其他线程,则当前线程等待。
这就是公平的体现吧:无论读写,都乖乖去排队,别插队。

其他内容后续学习补充~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值