ReentrantReadWriteLock原理分析

 在介绍ReentrantReadWriteLock读写锁原理之前,先来说下写锁与读锁。方便后续大家的理解。

1、当资源被写锁占用时,此时是不允许去读的。只有当写锁被释后读锁才能去申请资源、

2、当资源没有被写锁占用时,多个线程是可以共享资源。

写锁必须是是单个线程去进行写、当一个线程在对资源进行写操作时、另外的线程必须等待。这时刚好用到了AQS的两种锁模式:共享模式和独占模式。readLock就是基于AQS的是共享模式设计的。writeLock是基础AQS的独占模式进行设计。下面我们对源码进行较深入的分析。直接看代码的注释。

ReentrantReadWriteLock 实现了ReadWriteLock接口。

 //接口就两个方法一个读锁的方法 一个写锁的方法
public interface ReadWriteLock {
    Lock readLock();
    Lock writeLock();
}

ReentrantReadWriteLock 的构造方法 

   //构造方法支持公平锁和非公平锁的创建。(默认为非公平锁。效率更高)初始化读写锁   
   // ReadLock 与 WriteLock 是其内部类
   public ReentrantReadWriteLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
        readerLock = new ReadLock(this);
        writerLock = new WriteLock(this);
    }

    public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
    public ReentrantReadWriteLock.ReadLock  readLock()  { return readerLock; }

 ReadLock的初始化

    public static class ReadLock implements Lock, java.io.Serializable {
        private static final long serialVersionUID = -5992448646407690164L;
        private final Sync sync;
        
        //通过内部类SYN继承于AQS来实现读锁
        protected ReadLock(ReentrantReadWriteLock lock) {
            sync = lock.sync;
        }

     接下来看下syn非公平锁的实现
    abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = 6317671515068378041L;

        // 分享的划分,将32位划分为高16位和低16位 高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;

         //SHARED_UNIT    的值为
        // 0000 0000 0000 0001 0000 0000 0000 0000
        // MAX_COUNT      的值为 即65535 2的16次方-1
        //   0000 0000 0000 0000 1111 1111 1111 1111
      
        //sharedCount 
       // 假设c=1 c无符号右移 16位 高位补0无论正负
       //  0000 0000 0000 0000 0000 0000 0000 0001
       // sharedCount 返回的值为
       //  0000 0000 0000 0001 0000 0000 0000 0000

        static int sharedCount(int c)    { return c >>> SHARED_SHIFT; }
     //  exclusiveCount的值 真值表:1&0=0 1&1=1 0&0=0 0&1=0
     //  0000 0000 0000 0000 0000 0000 0000 0001 &
     //  0000 0000 0000 0000 1111 1111 1111 1111
     //   得到的值为  0000 0000 0000 0000 0000 0000 0000 0001 为1  
        static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }

接下来看ReadLock是怎么上锁的

       public void lock() {
            sync.acquireShared(1);
        }

     public final void acquireShared(int arg) {
        if (tryAcquireShared(arg) < 0)
            doAcquireShared(arg);
     }
    
       protected final int tryAcquireShared(int unused) {
 
            Thread current = Thread.currentThread();
            int c = getState();
         // 独占模式下线程数量 即 写锁的state值不为0
         // 如果写锁被占用 并且占用写锁的线程不是当前线程 那么返回-1
            if (exclusiveCount(c) != 0 &&
                getExclusiveOwnerThread() != current)
                return -1;
            // r 是读锁的数量  r < MAX_COUNT 小于最大的数量 65536 
           // !readerShouldBlock() 读锁申请是否需要等待、资源是否被写锁占用 后面详细讲
          // CAS 操作成功  compareAndSetState(c, c + SHARED_UNIT))在高16位的基础上操作 操作读锁
            int r = sharedCount(c);
            if (!readerShouldBlock() &&
                r < MAX_COUNT &&
                compareAndSetState(c, c + SHARED_UNIT)) {
                 // r==0 表示 读锁没有被占用
                 if (r == 0) {
                     // 标记第一个读锁的是当前线程
                    firstReader = current;
                    firstReaderHoldCount = 1;
                } else if (firstReader == current) {
                    // 读锁可重入
                     firstReaderHoldCount++;
                } else {
                    // 如果读锁的状态不为0 即有其他线程正在读取资源
                    HoldCounter rh = cachedHoldCounter;
                    //如果HoldCounter 一直为空或者不为 当前线程
                    if (rh == null || rh.tid != getThreadId(current))
                         // cachedHoldCounter 存入当前值
                        cachedHoldCounter = rh = readHolds.get();
                    else if (rh.count == 0)
                        // readHold设置当前值 一直是第一个值
                        readHolds.set(rh);
                       // count+1
                       rh.count++;
                }
                return 1;
            }
             // 当有写锁正在占用资源的时候、进入该方法
            return fullTryAcquireShared(current);
        }


    //上述的readerShouldBlock源码
    // 判断同步队列中 头部节点不为空 并且第二个节点不为空 并且头部接口以独占模式等待、返回true
    // 说明写锁已经获取到锁资源,并且还有其他线程正在申请写锁 、read锁资源直接失败
    final boolean apparentlyFirstQueuedIsExclusive() {
        Node h, s;
        return (h = head) != null &&
            (s = h.next)  != null &&
            !s.isShared()         &&
            s.thread != null;
    }

  // 当资源被写锁占用的时候调用fullTryAcquireShared
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;
                }
            }
        }

如果上面tryAcquireShared(arg) < 0条件成立,那么尝试获取读锁的资源失败

那么执行doAcquireShared方法。将当前线程添加到同步队列中的尾部 自旋尝试去获取读锁资源

接下来我们来看下释放读锁的源码

        public void unlock() {
            sync.releaseShared(1);
        }

        public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
       }

      protected final boolean tryReleaseShared(int unused) {
            Thread current = Thread.currentThread();
            // 对HoldCounter 缓存的一些信息进行操作
            // 释放当前线程的信息
            if (firstReader == current) {
          
                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))
                    // 当所有的读锁都释放掉了以后返回true 执行doReleaseShared方法
                    return nextc == 0;
            }
        }


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

接下来看writeLock的上锁源码 写锁就是独占模式的上锁。源码比较简单

        public void lock() {
            sync.acquire(1);
        }

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

 protected final boolean tryAcquire(int acquires) {
     
            Thread current = Thread.currentThread();
            int c = getState();
            int w = exclusiveCount(c);
            // C不为0 说明锁被占用,要么是读锁 要么是写锁
            if (c != 0) {
                // 如果写锁w状态值为0 或者占用写锁的不是当前线程 返回false 加入到等待队列中尝试获取锁
                if (w == 0 || current != getExclusiveOwnerThread())
                    return false;
                 
                if (w + exclusiveCount(acquires) > MAX_COUNT)
                    throw new Error("Maximum lock count exceeded");
                // 设置写锁的state状态为1 写锁成功
                setState(c + acquires);
                return true;
            }
            if (writerShouldBlock() ||
                !compareAndSetState(c, c + acquires))
                return false;
            setExclusiveOwnerThread(current);
            return true;
        }

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值