ReentrantReadWriteLock源码分析

     ReentrantLock中,线程都是以独占的方式来获得锁,但是在很多情况下,比如读多写少的情况,使用独占的方式明显不合适,读和读之间不会修改共享资源,可以保证不会出现问题,这种情况下使用ReentrantReadWriteLock会更合适。读线程之间使用共享锁,写写和写读之间使用独占锁。ReentrantReadWriteLock的类结构如下图所示:


      其中Syn实现了AQS中的一些比较重要的方法,比如lock和release,这里包括独占的方式和共享的方式两种。NonfairSyn和FairSyn是公平锁和非公平锁的实现,主要包括两个方法。ReadLock和WriteLock是对Syn类中的方法进行再一次的封装,函数体都非常简单。

特性

1.公平性:读操作之间不互斥,所以没有公平非公平这么一说。写操作在非公平锁中,写锁总是最先获得锁。而在公平锁中,只根据在CLH队列中等待的时间来分配锁。

2.重入性:读操作获得读锁之后可以再次获得读锁,写锁同理。但是读锁不能被写锁重入,写锁可以获得读锁,这就是锁降级。

3.可中断:提供可以响应中断的锁。

参数及构造函数

    /** 通过内部类来获得读锁 */
    private final ReentrantReadWriteLock.ReadLock readerLock;
    /** 获得写锁*/
    private final ReentrantReadWriteLock.WriteLock writerLock;
    /** Performs all synchronization mechanics */
    final Sync sync;

    /**
     * 默认是非公平锁,因为这样吞吐量更大.
     */
    public ReentrantReadWriteLock() {
        this(false);
    }

    /**
     * 可以在构造函数中设置公平或者是非公平
     * @param fair {@code true} if this lock should use a fair ordering policy
     */
    public ReentrantReadWriteLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
        readerLock = new ReadLock(this);
        writerLock = new WriteLock(this);
    }

和reentrantLock不一样的地方在于把原来的state拆成了两份。

  /*
         *通过将state状态分为高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; }

写锁的读取和释放

写锁由于是独占锁,其获取和释放相对读锁更加简单。写锁的获取和释放都在Syn中实现。

  首先会获得当前锁的数量,然后在通过位操作获得相应的写锁个数,并根据相应条件进行判断是否这个线程可以获得写锁。

 /**
     * 获得锁成功则退出,不成功则添加节点到CLH队列尾部,然后执行acquireQueued循环尝试获取锁,这里和reentrantLock 类似。
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        {@link #tryAcquire} but is otherwise uninterpreted and
     *        can represent anything you like.
     */
    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }
protected final int tryAcquireShared(int unused) { //尝试获取资源 /* * */
        Thread current = Thread.currentThread();
        int c = getState();
        if (exclusiveCount(c) != 0 && //当期写锁不为0 或者是写锁占有了线程 返回-1 
                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;//读锁个数为0 设置头读节点和持有数量 
            } 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);//读锁被阻塞导致的失败,继续执行下面函数来获取锁 }

    }
 protected final boolean tryAcquire(int acquires) {
            /*
             * Walkthrough:
             * 1. 读锁个数不是0或者写锁个数不是0或者当前线程不是持有锁的线程,失败。
             * 2. 如果锁个数大于最大值,失败
             * 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;//读锁不为0,写锁为0,失败
                if (w + exclusiveCount(acquires) > MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");//个数太多,失败
                // Reentrant acquire
                setState(c + acquires);//其他都是成功,返回新的状态值
                return true;
            }
            if (writerShouldBlock() || //锁的个数为0 判断是否需要阻塞 ,write总是返回false
                !compareAndSetState(c, c + acquires))
                return false;
            setExclusiveOwnerThread(current);//设置排他线程。
            return true;
        }
写锁释放也比较简单,判断线程是否正确,判断锁的个数是否为0.
 /*
         * Note that tryRelease and tryAcquire can be called by
         * Conditions. So it is possible that their arguments contain
         * both read and write holds that are all released during a
         * condition wait and re-established in tryAcquire.
         */

        protected final boolean tryRelease(int releases) {
            if (!isHeldExclusively())//如果当前线程不是持有线程则抛出异常。
                throw new IllegalMonitorStateException();
            int nextc = getState() - releases;//重新计算锁的个数
            boolean free = exclusiveCount(nextc) == 0;//锁的个数中低16位锁个数为0 则设置排他线程为空
            if (free)
                setExclusiveOwnerThread(null);
            setState(nextc);
            return free;
        }



读锁的获取比较复杂。下面是读锁获取的简单流程。


 /**
     * 忽略中断,以共享的模式获取锁  Implemented by
     * first invoking at least once {@link #tryAcquireShared},
     * returning on success.  Otherwise the thread is queued, possibly
     * repeatedly blocking and unblocking, invoking {@link
     * #tryAcquireShared} until success.
     *
     * @param arg the acquire argument.  This value is conveyed to
     *        {@link #tryAcquireShared} but is otherwise uninterpreted
     *        and can represent anything you like.
     */
    public final void acquireShared(int arg) {
        if (tryAcquireShared(arg) < 0)//尝试获取锁,如果没有获得,就做一些尝试操作
            doAcquireShared(arg);
    }
   /**
         * Full version of acquire for reads, that handles CAS misses
         * and reentrant reads not dealt with in tryAcquireShared.
         */
        final int fullTryAcquireShared(Thread current) {
            /*
             * This code is in part redundant with that in
             * tryAcquireShared but is simpler overall by not
             * complicating tryAcquireShared with interactions between
             * retries and lazily reading hold counts.
             */
            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()) {//写锁为0 读锁几遍被阻塞也要执行,不然死锁
                    // 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;
                    }
                }//成功获取读锁,如果是头读节点则状态加一,否则和tryAcquired成功获取锁一样。
                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;
                }
            }
        }

 /**
     * 读锁获取资源失败后,添加这个线程作为一个节点放在后面,然后不断获取前驱节点,当前驱节点是head节点时,尝试获取资源
     * 否则,判断当前线程是不是应该阻塞,然后阻塞之。
     */
    private void doAcquireShared(int arg) {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        if (interrupted)
                            selfInterrupt();
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }


   读锁的释放相对简单,首先尝试释放资源,如果可以的话尝试唤醒后继节点。尝试释放资源的过程中,如果当前节点是头读节点,并且持有锁的数量为1,那么释放资源之后头读节点就是null了,否则将持有节点数量减一。


 /**
     * Releases in shared mode.  Implemented by unblocking one or more
     * threads if {@link #tryReleaseShared} returns true.
     *
     * @param arg the release argument.  This value is conveyed to
     *        {@link #tryReleaseShared} but is otherwise uninterpreted
     *        and can represent anything you like.
     * @return the value returned from {@link #tryReleaseShared}
     */
    public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }
  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;//如果锁为0,可以唤醒后面的写锁了。
            }
        }
 /**
     * Release action for shared mode -- signals successor and ensures
     * propagation. (Note: For exclusive mode, release just amounts
     * to calling unparkSuccessor of head if it needs signal.)
     */
    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;
        }
    }


参考资料:

https://my.oschina.net/adan1/blog/158107

https://www.jianshu.com/p/d47fe1ec1bb3

https://www.jianshu.com/p/9f98299a17a5(写的很详细)

http://ifeve.com/juc-reentrantreadwritelock/




猜你喜欢

转载自blog.csdn.net/pb_yan/article/details/80572194