并发包源码解读——ReentrantReadWriteLock

写在前面:

读写锁也是分公平/非公平的,由于上一章已经讲了公平锁和非公平锁的区别,而且也说明了非公平锁使用率更高的原因,那么我们主要以介绍非公平锁实现逻辑为主

可以先告诉大家一个结论,这样方便理解:不同线程读读并存,读写互斥,写写互斥

1、构造器

读写锁的构造器很简单,就是先初始化一个公平/非公平锁,然后再根据这个锁构造读锁和写锁

public ReentrantReadWriteLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
        readerLock = new ReadLock(this);
        writerLock = new WriteLock(this);
    }

2、写锁实现逻辑

2.1、尝试获取锁——tryAcquire

调用lock方法,它是acquire方法的封装

public void lock() {
            sync.acquire(1);
        }
public final void acquire(int arg) {
    if (!tryAcquire(arg) &&
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}

首先调用tryAcquire方法

protected final boolean tryAcquire(int acquires) {
    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;
}

前两步没什么可说的,获取当前线程并获取写锁状态

看第三步exclusiveCount,翻译过来是“独占计数”,意思就是加了独占锁的次数,这里介绍一下,ReentrantReadWriteLock是以2个16进制存储读写锁计数的,高16位存读,低16位存写,所以exclusiveCount是取低16位写的次数

static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
2.1.1、获取写锁(有占用)

state不等于0时,说明锁被占用,进入条件判断

第一步:通过exclusiveCount获取加写锁的次数。加写锁的次数为0说明之前线程加的是读锁(state不为0但是取低16位为0,说明高16位不为0,高16位表示加读锁次数),如果前一个线程加的是读锁,或者前一个线程加的写锁但是跟当前线程不是一个线程,则获取锁失败;如果是同一个线程,符合可重入锁规则,就更新加锁次数,返回加锁成功

2.1.2、获取写锁(无占用)

state为0时,说明还没有线程占用锁,所以直接跳过第一个if判断,进入writerShouldBlock

非公平锁的writerShouldBlock直接返回false,说明写锁不需要判断前面是否还有线程排队阻塞阻塞,可以直接进入compareAndSetState抢锁

static final class NonfairSync extends Sync {
        private static final long serialVersionUID = -8159625535654395037L;
        final boolean writerShouldBlock() {
            return false; // writers can always barge
        }
        final boolean readerShouldBlock() {
            return apparentlyFirstQueuedIsExclusive();
        }
    }

最后执行setExclusiveOwnerThread缓存当前拥有锁的线程

2.2、阻塞排队——acquireQueued

在获取锁失败的时候,将线程放入队列中,过程与ReetrantLock相同,此处省略

###2.3、释放写锁——unlock

释放写锁,调用unlock方法,它是release方法的封装

public void unlock() {
            sync.release(1);
        }
public final boolean release(int arg) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

调用tryRelease方法尝试释放锁

首先isHeldExclusively校验请求解锁的当前线程是否为锁持有者

然后更新加锁次数,如果释放锁之后已经没有写锁了,还要把锁持有者置空

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 isHeldExclusively() {
            return getExclusiveOwnerThread() == Thread.currentThread();
        }

释放锁成功的话,回到release方法,如果队列中还有线程再等待,还要调用unparkSuccessor主动唤醒一下,这部分逻辑和ReetrantLock类似,就略过了

3、读锁实现逻辑

3.1、尝试获取锁——lock

获取读锁调用lock方法,它是acquireShared方法的封装

public void lock() {
            sync.acquireShared(1);
        }
public final void acquireShared(int arg) {
        if (tryAcquireShared(arg) < 0)
            doAcquireShared(arg);
    }

首先调用tryAcquireShared

当加了写锁(exclusiveCount© != 0)并且锁持有者的不是当前线程,返回-1

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);
        }

否则通过sharedCount取高16位加读锁的次数

接着调用readerShouldBlock,它是apparentlyFirstQueuedIsExclusive方法的封装

这个方法达到了调高写锁优先级的效果(判断读锁是否需要阻塞),nextWaiter表示下个节点是否可以与该节点共享,是在尝试获取锁失败时初始化的。当等待队列头节点的nextWaiter是EXCLUSIVE(null)而不是SHARD时,说明队列中的第一个节点正准备获取写锁,此时到来的获取读锁的线程是不能跟写锁抢锁的

static final class NonfairSync extends Sync {
        private static final long serialVersionUID = -8159625535654395037L;
        final boolean writerShouldBlock() {
            return false; // writers can always barge
        }
        final boolean readerShouldBlock() {
            return apparentlyFirstQueuedIsExclusive();
        }
    }
final boolean apparentlyFirstQueuedIsExclusive() {
    Node h, s;
    return (h = head) != null &&
        (s = h.next)  != null &&
        !s.isShared()         &&
        s.thread != null;
}
final boolean isShared() {
            return nextWaiter == SHARED;
        }
static final class Node {
        /** Marker to indicate a node is waiting in shared mode */
        static final Node SHARED = new Node();
        /** Marker to indicate a node is waiting in exclusive mode */
        static final Node EXCLUSIVE = null;
}

读锁抢到了就返回成功,失败了就进入fullTryAcquireShared

这个方法一上来就是一个for死循环,当满足获取到了读锁/获取不到读锁的结果就会返回

那我们按代码顺序捋捋这几种返回情况:

1、加写锁的线程不是自己,返回加锁失败

2、加写锁的线程就是自己,肯定也允许当前线程加读锁(锁降级),就CAS尝试更新一下加读锁的次数,更新成功了就返回加锁成功,更新失败了就进入下一次for循环

此处补充一下锁降级的作用:一个线程执行完共享资源的更新后,需要先加读锁阻塞其他线程(防止其他线程对共享资源更新,对当前线程使用共享资源有影响),再释放写锁(防止其他线程获取读锁时阻塞,提高响应),当前线程执行完使用逻辑后再释放读锁

3、如果判断当前没加写锁,有可能就有后面的线程尝试获取写锁并先于该线程进入等待队列,所以要用readerShouldBlock提高写锁的优先级

如果现在拥有读锁的线程就是自己,那就直接执行后面的代码,读重入锁次数加一

如果现在拥有读锁的线程不是自己,那就获取成功,同时更新缓存(最后一次成功获取读锁的线程)

final int fullTryAcquireShared(Thread current) {
            HoldCounter rh = null;
            for (;;) {
                int c = getState();
                //1
                if (exclusiveCount(c) != 0) {
                    if (getExclusiveOwnerThread() != current)
                        return -1;
                } else if (readerShouldBlock()) {
                    if (firstReader == current) {
                        
                    } 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");
              //2
                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;
                }
            }
        }

补充:cachedHoldCounter

HoldCounter是一个计数器,用来缓存当前线程的id以及当前线程获取读锁的次数

cachedHoldCounter作为共享变量,用来缓存最近一次成功获取读锁的线程对应的计数器。好处是在部分情况下提高性能,避免每次都从ThreadLocal中取

private transient HoldCounter cachedHoldCounter;

static final class HoldCounter {
            int count = 0;
            // Use id, not reference, to avoid garbage retention
            final long tid = getThreadId(Thread.currentThread());
        }

补充:readHolds

继承了ThreadLocal类,主要是用来缓存每个线程对应的HoldCounter

private transient ThreadLocalHoldCounter readHolds;

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

回到tryAcquire方法,如果acquireShared方法返回-1尝试获取读锁失败,就进入doAcquireShared,方法跟ReetrantLock类似,不再赘述

3.2、释放读锁——unlock

调用unlock方法,它是releaseShared方法的封装

public void unlock() {
            sync.releaseShared(1);
        }
public final boolean releaseShared(int arg) {
    if (tryReleaseShared(arg)) {
        doReleaseShared();
        return true;
    }
    return false;
}

首先调用tryReleaseShared方法

如果队列中获取读锁的第一个线程(firstReader)就是自己,说明是重入读锁,直接维护读锁的首个线程和计数器,计数器-1,降到1说明只有一个读锁了,就把firstReader清掉

如果第一个加读锁的线程不是自己,那自己肯定不能释放别的线程的锁,那我们就只能维护当前读锁的计数器,改减减,该移除移除

最后维护state状态,读锁次数-1,注意一点,自己的读锁释放完了不是真正的释放读锁,只有释放自己的读锁之后读锁空闲时才能叫真正的释放读锁,所以在自己的读锁释放完了之后,如果发现还有读锁,返回释放锁失败

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;
            }
            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;
            }
        }

如果尝试释放锁成功了,则进入doReleaseShared方法,维护队列中节点的状态

private void doReleaseShared() {
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }

这篇博客到此就结束了,如果我有写的不对的地方,或者你有什么不懂得地方,欢迎发表评论随时交流,喜欢的点个赞

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wheat_Liu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值