ReentrantReadWriteLock源码解析

原理

  1. 共享锁(读锁)与独占锁(写锁)锁互斥
  2. 读锁获取资源时,其他线程可以读锁获取资源,可重入。
  3. 写锁获取资源时,只有获取写锁的线程可以再次加锁即锁重入。
  4. 获取写锁的线程还可以获取读锁,写锁释放即锁降级。

源码

ReentrantReadWriteLock源码

ReentrantReadWriteLock中有ReadLock和WriteLock,使用时新建ReentrantReadWriteLock对象,默认非公平锁,通过其readLock()和writeLock()方法来获得读锁和写锁。

public class ReentrantReadWriteLock
       implements ReadWriteLock, java.io.Serializable {
   private static final long serialVersionUID = -6992448646407690164L;
   /** Inner class providing readlock */
   private final ReentrantReadWriteLock.ReadLock readerLock;
   /** Inner class providing writelock */
   private final ReentrantReadWriteLock.WriteLock writerLock;
   /** Performs all synchronization mechanics */
   final Sync sync;

   /**
    * Creates a new {@code ReentrantReadWriteLock} with
    * default (nonfair) ordering properties.
    */
   public ReentrantReadWriteLock() {
       this(false);
   }

   /**
    * Creates a new {@code ReentrantReadWriteLock} with
    * the given fairness policy.
    *
    * @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);
   }

读写锁的锁获取原理以及获取后的锁计数更在Sync类中实现。

abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 6317671515068378041L;

        /*
         * Read vs write count extraction constants and functions.
         * Lock state is logically divided into two unsigned shorts:
         * The lower one representing the exclusive (writer) lock hold count,
         * and the upper the shared (reader) hold count.
         */
        //位移,用来通过位运算获取32位int型锁计数的高位与低位
        static final int SHARED_SHIFT   = 16;
        //左移16位,一个读锁的单元,
        static final int SHARED_UNIT    = (1 << SHARED_SHIFT);
        //读锁和写锁的最大数量
        static final int MAX_COUNT      = (1 << SHARED_SHIFT) - 1;
        //高位全0,低位全1,通过与锁计数数值进行&运算,获取低位数值,即写锁数量
        static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;

        /** Returns the number of shared holds represented in count  */
        //获得c的高位值,读锁数量
        static int sharedCount(int c)    { return c >>> SHARED_SHIFT; }
        /** Returns the number of exclusive holds represented in count  */
        //获得c的低位值,写锁数量
        static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }

       
        /*
         * Acquires and releases use the same code for fair and
         * nonfair locks, but differ in whether/how they allow barging
         * when queues are non-empty.
         */

        /**
         * Returns true if the current thread, when trying to acquire
         * the read lock, and otherwise eligible to do so, should block
         * because of policy for overtaking other waiting threads.
         */
        abstract boolean readerShouldBlock();

        /**
         * Returns true if the current thread, when trying to acquire
         * the write lock, and otherwise eligible to do so, should block
         * because of policy for overtaking other waiting threads.
         */
        abstract boolean writerShouldBlock();

        /*
         * 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;
            //如果写锁全部释放,删除记录的获取写锁的线程
            if (free)
                setExclusiveOwnerThread(null);
            //更新锁计数状态
            setState(nextc);
            return free;
        }
        //获取写锁
        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) {
                //如果其他线程获取的不是写锁(即获取了读锁),或当前线程不是获取写锁的线程,则获取写锁失败
                // (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;
            }
            //若不曾被线程获取过,考虑到并发环境,由修改锁计数成功的线程获取写锁,writerShouldBlock()为公平锁与非公平锁区别
            //非公平锁中总是返回false,即获取写锁不会阻塞。
            if (writerShouldBlock() ||
                !compareAndSetState(c, c + acquires))
                return false;
            setExclusiveOwnerThread(current);
            return true;
        }

         /**
         * A counter for per-thread read hold counts.
         * Maintained as a ThreadLocal; cached in cachedHoldCounter
         */
        //记录每个获取读锁线程的重入次数
        //保存在Threadlocal中,上次使用的会缓存在cachedHoldCounter里
        static final class HoldCounter {
            int count = 0;
            // Use id, not reference, to avoid garbage retention
            final long tid = getThreadId(Thread.currentThread());
        }

        /**
         * ThreadLocal subclass. Easiest to explicitly define for sake
         * of deserialization mechanics.
         */
        static final class ThreadLocalHoldCounter
            extends ThreadLocal<HoldCounter> {
            public HoldCounter initialValue() {
                return new HoldCounter();
            }
        }

        /**
         * The number of reentrant read locks held by current thread.
         * Initialized only in constructor and readObject.
         * Removed whenever a thread's read hold count drops to 0.
         */
        //获取当前线程读锁计数器的threadlocal
        private transient ThreadLocalHoldCounter readHolds;

        /**
         * The hold count of the last thread to successfully acquire
         * readLock. This saves ThreadLocal lookup in the common case
         * where the next thread to release is the last one to
         * acquire. This is non-volatile since it is just used
         * as a heuristic, and would be great for threads to cache.
         *
         * 

Can outlive the Thread for which it is caching the read * hold count, but avoids garbage retention by not retaining a * reference to the Thread. * *

Accessed via a benign data race; relies on the memory * model's final field and out-of-thin-air guarantees. */ //暂存上一次某个线程的读锁计数器,如果这次在释放或重入时刚好是该线程,则省去了从threadlocal中获取读锁计数器的步骤 private transient HoldCounter cachedHoldCounter; /** * firstReader is the first thread to have acquired the read lock. * firstReaderHoldCount is firstReader's hold count. * *

More precisely, firstReader is the unique thread that last * changed the shared count from 0 to 1, and has not released the * read lock since then; null if there is no such thread. * *

Cannot cause garbage retention unless the thread terminated * without relinquishing its read locks, since tryReleaseShared * sets it to null. * *

Accessed via a benign data race; relies on the memory * model's out-of-thin-air guarantees for references. * *

This allows tracking of read holds for uncontended read * locks to be very cheap. */ private transient Thread firstReader = null; private transient int firstReaderHoldCount; Sync() { readHolds = new ThreadLocalHoldCounter(); setState(getState()); // ensures visibility of readHolds } //释放读锁 protected final boolean tryReleaseShared(int unused) { Thread current = Thread.currentThread(); if (firstReader == current) { //如果是排序第一的获取读锁的线程 // assert firstReaderHoldCount > 0; //线程持有读锁量(重入次数)为1,线程释放锁 if (firstReaderHoldCount == 1) firstReader = null; else //大于1,重入次数减1 firstReaderHoldCount--; } else { //不是第一个获取读锁的线程,其读锁计数器需要从threadlocal中获取 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; } } private IllegalMonitorStateException unmatchedUnlockException() { return new IllegalMonitorStateException( "attempt to unlock read lock, not locked by current thread"); } //获取读锁 protected final int tryAcquireShared(int unused) { /* * Walkthrough: * 1. If write lock held by another thread, fail. * 2. Otherwise, this thread is eligible for * lock wrt state, so ask if it should block * because of queue policy. If not, try * to grant by CASing state and updating count. * Note that step does not check for reentrant * acquires, which is postponed to full version * to avoid having to check hold count in * the more typical non-reentrant case. * 3. If step 2 fails either because thread * apparently not eligible or CAS fails or count * saturated, chain to version with full retry loop. */ Thread current = Thread.currentThread(); int c = getState(); //如果已有写锁且当前线程不是获取写锁线程,加锁失败 //说明写锁线程可以再获取读锁 if (exclusiveCount(c) != 0 && getExclusiveOwnerThread() != current) return -1; //读锁数量 int r = sharedCount(c); //如果不阻塞,且读锁数量小于最大数量,且cas成功 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; } //如果阻塞,或者获取失败,则使用cas循环获取 return fullTryAcquireShared(current); } /** * 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()) { // 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)) { //这里c中记录的读锁数量不可能为0,sharedCount(c)>0 if (sharedCount(c) == 0) { firstReader = current; firstReaderHoldCount = 1; } else if (firstReader == current) { //如果是第一个获取读锁的线程,重入数+1 firstReaderHoldCount++; } else { //其他线程的话,需要充threadlocal中获取读锁计数并+1 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++; //方便下次释放时,如果刚好是该线程,不需要再去threadlocal中获取读锁计数 cachedHoldCounter = rh; // cache for release } return 1; } } } /** * Performs tryLock for write, enabling barging in both modes. * This is identical in effect to tryAcquire except for lack * of calls to writerShouldBlock. */ //与tryAcquire()一致 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; } /** * Performs tryLock for read, enabling barging in both modes. * This is identical in effect to tryAcquireShared except for * lack of calls to 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; } } } protected final boolean isHeldExclusively() { // While we must in general read state before owner, // we don't need to do so to check if current thread is owner return getExclusiveOwnerThread() == Thread.currentThread(); } // Methods relayed to outer class final ConditionObject newCondition() { return new ConditionObject(); } final Thread getOwner() { // Must read state before owner to ensure memory consistency return ((exclusiveCount(getState()) == 0) ? null : getExclusiveOwnerThread()); } final int getReadLockCount() { return sharedCount(getState()); } final boolean isWriteLocked() { return exclusiveCount(getState()) != 0; } final int getWriteHoldCount() { return isHeldExclusively() ? exclusiveCount(getState()) : 0; } final int getReadHoldCount() { if (getReadLockCount() == 0) return 0; Thread current = Thread.currentThread(); if (firstReader == current) return firstReaderHoldCount; HoldCounter rh = cachedHoldCounter; if (rh != null && rh.tid == getThreadId(current)) return rh.count; int count = readHolds.get().count; if (count == 0) readHolds.remove(); return count; } /** * Reconstitutes the instance from a stream (that is, deserializes it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); readHolds = new ThreadLocalHoldCounter(); setState(0); // reset to unlocked state } final int getCount() { return getState(); } }

NonfairSync(非公平锁)与FairSync(公平锁)继承了Sync,作为ReentrantReadWriteLock的具体成员变量。他们的不同在于阻塞方法的不同。

    /**
     * Nonfair version of Sync
     */
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = -8159625535654395037L;
        final boolean writerShouldBlock() {
            return false; // writers can always barge
        }
        final boolean readerShouldBlock() {
            /* As a heuristic to avoid indefinite writer starvation,
             * block if the thread that momentarily appears to be head
             * of queue, if one exists, is a waiting writer.  This is
             * only a probabilistic effect since a new reader will not
             * block if there is a waiting writer behind other enabled
             * readers that have not yet drained from the queue.
             */
            return apparentlyFirstQueuedIsExclusive();
        }
    }

    /**
     * Fair version of Sync
     */
    static final class FairSync extends Sync {
        private static final long serialVersionUID = -2274990926593161451L;
        final boolean writerShouldBlock() {
            return hasQueuedPredecessors();
        }
        final boolean readerShouldBlock() {
            return hasQueuedPredecessors();
        }
    }

Sync继承了AbstractQueuedSynchronizer,AbstractQueuedSynchronizer中主要实现了等待线程队列。

你可能感兴趣的:(Java基础)