JUC读写锁原理一

ReentrantReadWriteLock

干啥的?
将原来的互斥锁,切割为两把锁:读锁+写锁,为什么要切割?考虑一下:三个线程A,B,C,其中线程A和B为读取变量的线程,而C为修改变量的线程,且C很少去修改变量,此时为什么要让A和B线程去争用互斥锁呢?因为此时它两并不修改变量,所以同时并发读取是没有任何问题的,所以我们把锁切割为了两把,当读时,获取读锁,写时获取写锁,且读锁可以多个线程同时获取,此时我们称读锁为共享锁,写锁为互斥锁。

其中读写为两个状态,所以我们应该有两个变量来表示写锁和读锁的状态
int writeState;
int readState;
为什么用整型值?因为读写锁均是可重入的,也即一个线程在获取到锁之后,可以再次获取锁。
表示写锁(互斥锁):
if readState == 0
if CAS writeState 0=>1
return;
else currentThread == writeThread //当前 获取锁的线程是不是当前线程
writeState++
return;

表示读锁(共享锁)此处的读锁并没有共享,并且由于此处没上锁,别的线程拿到了线程把writeState给改了
if writeState == 0
if CAS readState 0=>1
return;
else currentThread == readThread //当前 获取锁的线程是不是当前线程
readState++
return;

由于拆分成了两个变量,所以此时以下两个操作不是原子性的,可能会导致一个线程既获取到了读锁也获取到了写锁。
所以引入了lockState变量来保证原子性:自旋锁 lockState。

如下方式就没问题了,通过lock LockState方式来控制其原子性,只让单线程访问
lock LockState
if readState == 0
if CAS writeState 0=>1
return;
else currentThread == writeThread //当前 获取锁的线程是不是当前线程
writeState++
return;

表示读锁(共享锁)
lock LockState
if writeState == 0 //假如这里有很多线程都是读线程,写线程是否会永远获取不到锁(造成线程饥饿)
解决:在获取读锁之前判断是否有写锁排队
if readState++
else
此时有个 int state的变量
32位的变量,此时我们考虑切割为高16位+低16位,分别用于表示读锁和写锁,此时由于只需要操作一个变量,所以只需要一个CAS即可,不需要保证多个操作完成的原子性

根据源码可以看出读写锁默认为非公平锁,非公平锁的效率是大于公平锁的(因为不需要进行线程间的切换)

如果我想要知道当前线程获取到了多少次共享锁,也即重入了多少次共享锁怎么办?
因为state的高16位是所有读线程共享的位,通过ThreadLocal来记录每个线程获取了多少次共享锁,所以我们称state的高十六位用于存储所有读线程获取共享锁的次数,ThreadLocal用于表示当前线程自己的重入次数。SUM(All Thread’s ThreadLocal) = state>>16;
写锁不需要记录进ThreadLocal,因为写锁互斥的,用State的低16即可。

假如:所有时间,都是同一个线程获取读锁,那么有没有必要使用ThreadLocal?因为ThreadLocal占用内存,有必要吗?
没必要,所以我们做一个优化,在读写锁中维护一个:first获取读锁的变量和线程对象即可。
在这里插入图片描述

  /**
         * A counter for per-thread read hold counts.
         * Maintained as a ThreadLocal; cached in 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();
            }
        }

如上源码HoldCounter,用来计数每个线程持有读锁的数量,通过ThreadLocal来维护,
HoldCounter 里面使用了一个tid,这里没使用当前线程的引用的原因在于去避免垃圾回收,由于ThreadLocalHoldCounter缓存到了它,结果就会造成垃圾回收回收不了那个线程对象。

在这里插入图片描述
如上代码通过setState写一个volatile的变量,可以保证前面的readHolds也具备了可见性。

来看获取共享锁的源码:

        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();
            //获取读锁的时候已经有线程获取写锁了,此时进一步判断当前获取写锁的线程是不是它,如果不是返回-1直接阻塞
            if (exclusiveCount(c) != 0 &&
                getExclusiveOwnerThread() != current)
                return -1;
          //获取共享锁的数量      
            int r = sharedCount(c);
            //判断读者应不应该被阻塞(非公平锁:判断当前等待的第一个是不是写者,防止写锁饥饿  2、公平锁:队列的前面有没有等待者,有就排队)
            if (!readerShouldBlock() &&
                r < MAX_COUNT &&
                //如果都满足条件通过cas对高十六位加1
                compareAndSetState(c, c + SHARED_UNIT)) {
       //如果当前线程是第一个读线程则直接初始化一个1         
                if (r == 0) {
                    firstReader = current;
                    firstReaderHoldCount = 1;
                } else if (
//如果一直是当前线程在读,那么直接加firstReaderHoldCount的数量
firstReader == current) {
                    firstReaderHoldCount++;
                } else {
//如果是别的线程拿到读锁,初始化一个别的ThreadLocal变量即可,然后加这个值即可
                    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);
        }

在进入fullTryAcquireShared()方法

   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.
                    //readerShouldBlock()判断读锁是否应该被阻塞
                } 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)
                                //由于此处的读是要被阻塞的,如果当前持有读锁的数量为0那么我们不需要这个变量了,直接remove掉
                                    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;
                }
            }
        }

锁的本质:是让一个CPU执行指令串的时候只能执行同一个指令串,其他线程无法切换,就算切换到其他线程也不能执行这段指令串,保证CPU在调度一个线程的时候,该线程执行的指令段,
只有当前线程可执行,其他线程无法执行
释放共享锁源码:

   protected final boolean tryReleaseShared(int unused) {
            Thread current = Thread.currentThread();
            //首先判断是不是第一个线程
            if (firstReader == current) {
                // assert firstReaderHoldCount > 0;
                //此处等于1代表已经是最后一次读锁,然后把他赋值为空
                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.
                    //如果为0代表读锁已经释放完毕,唤醒后面的写线程,如果不为0则不唤醒
                    return nextc == 0;
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值