Featured image of post 彻底搞懂AQS

彻底搞懂AQS

AQSAQS 核心思想是,如果被请求的共享资源空闲,则将当前请求资源的线程设置为有效的工作线程,并且将共享资

Image

AQS

AQS 核心思想是,如果被请求的共享资源空闲,则将当前请求资源的线程设置为有效的工作线程,并且将共享资源设置为锁定状态。如果被请求的共享资源被占用,那么就需要一套线程阻塞等待以及被唤醒时锁分配的机制,这个机制 AQS 是用 CLH 队列锁实现的,即将暂时获取不到锁的线程加入到队列中。

AQS定义了两种资源获取方式:独占(只有一个线程能访问执行,又根据是否按队列的顺序分为公平锁和非公平锁,如ReentrantLock) 和共享(多个线程可同时访问执行,如Semaphore/CountDownLatch,Semaphore、CountDownLatCh、 CyclicBarrier )。ReentrantReadWriteLock 可以看成是组合式,允许多个线程同时对某一资源进行读。

AQS底层使用了模板方法模式, 自定义同步器在实现时只需要实现共享资源 state 的获取与释放方式即可,至于具体线程等待队列的维护(如获取资源失败入队/唤醒出队等),AQS已经在上层已经帮我们实现好了。

同步器的可重写方法

Image

同步器的模板方法

Image

AQS框架:

Image

AQS模型如下图:

Image

双向链表中,第一个节点为虚节点,其实并不存储任何信息,只是占位。真正的第一个有数据的节点,是在第二个节点开始的。

Image

  • AQS state字段(int类型,32位),该字段用来描述有多少线程持有锁。

  • 在独享锁中这个值通常是0或者1(如果是重入锁的话state值就是重入的次数),在共享锁中state就是持有锁的数量.

  • 我们发现在ReentrantLock虽然有公平锁和非公平锁两种,但是它们添加的都是独享锁。根据源码所示,当某一个线程调用lock方法获取锁时,如果同步资源没有被其他线程锁住,那么当前线程在使用CAS更新state成功后就会成功抢占该资源。而如果公共资源被占用且不是被当前线程占用,那么就会加锁失败。所以可以确定ReentrantLock无论读操作还是写操作,添加的锁都是都是独享锁。

ReentrantReadWriteLock

在ReentrantReadWriteLock中有读、写两把锁,所以需要在一个整型变量state上分别描述读锁和写锁的数量(或者也可以叫状态)。于是将state变量“按位切割”切分成了两个部分,高16位表示读锁状态(读锁个数),低16位表示写锁状态(写锁个数

Image

获取写锁源码:

 1/**
 2         * 获取写锁
 3           Acquires the write lock.
 4         *  如果此时没有任何线程持有写锁或者读锁,那么当前线程执行CAS操作更新status,
 5         *  若更新成功,则设置读锁重入次数为1,并立即返回
 6         * <p>Acquires the write lock if neither the read nor write lock
 7         * are held by another thread
 8         * and returns immediately, setting the write lock hold count to
 9         * one.
10         *  如果当前线程已经持有该写锁,那么将写锁持有次数设置为1,并立即返回
11         * <p>If the current thread already holds the write lock then the
12         * hold count is incremented by one and the method returns
13         * immediately.
14         *  如果该锁已经被另外一个线程持有,那么停止该线程的CPU调度并进入休眠状态,
15         *  直到该写锁被释放,且成功将写锁持有次数设置为1才表示获取写锁成功
16         * <p>If the lock is held by another thread then the current
17         * thread becomes disabled for thread scheduling purposes and
18         * lies dormant until the write lock has been acquired, at which
19         * time the write lock hold count is set to one.
20         */
21        public void lock() {
22            sync.acquire(1);
23        }
24/**
25     * 该方法为以独占模式获取锁,忽略中断
26     * 如果调用一次该“tryAcquire”方法更新status成功,则直接返回,代表抢锁成功
27     * 否则,将会进入同步队列等待,不断执行“tryAcquire”方法尝试CAS更新status状态,直到成功抢到锁
28     * 其中“tryAcquire”方法在NonfairSync(公平锁)中和FairSync(非公平锁)中都有各自的实现
29     *
30     * Acquires in exclusive mode, ignoring interrupts.  Implemented
31     * by invoking at least once {@link #tryAcquire},
32     * returning on success.  Otherwise the thread is queued, possibly
33     * repeatedly blocking and unblocking, invoking {@link
34     * #tryAcquire} until success.  This method can be used
35     * to implement method {@link Lock#lock}.
36     *
37     * @param arg the acquire argument.  This value is conveyed to
38     *        {@link #tryAcquire} but is otherwise uninterpreted and
39     *        can represent anything you like.
40     */
41    public final void acquire(int arg) {
42        if (!tryAcquire(arg) &&
43            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
44            selfInterrupt();
45    }
46    protected final boolean tryAcquire(int acquires) {
47            /*
48             * Walkthrough:
49             * 1、如果读写锁的计数不为0,且持有锁的线程不是当前线程,则返回false
50             * 1. If read count nonzero or write count nonzero
51             *    and owner is a different thread, fail.
52             * 2、如果持有锁的计数不为0且计数总数超过限定的最大值,也返回false
53             * 2. If count would saturate, fail. (This can only
54             *    happen if count is already nonzero.)
55             * 3、如果该锁是可重入或该线程在队列中的策略是允许它尝试抢锁,那么该线程就能获取锁
56             * 3. Otherwise, this thread is eligible for lock if
57             *    it is either a reentrant acquire or
58             *    queue policy allows it. If so, update state
59             *    and set owner.
60             */
61            Thread current = Thread.currentThread();
62            //获取读写锁的状态
63            int c = getState();
64            //获取该写锁重入的次数
65            int w = exclusiveCount(c);
66            //如果读写锁状态不为0,说明已经有其他线程获取了读锁或写锁
67            if (c != 0) {
68                //如果写锁重入次数为0,说明有线程获取到读锁,根据“读写锁互斥”原则,返回false
69                //或者如果写锁重入次数不为0,且获取写锁的线程不是当前线程,根据"写锁独占"原则,返回false
70                // (Note: if c != 0 and w == 0 then shared count != 0)
71                if (w == 0 || current != getExclusiveOwnerThread())
72                    return false;
73               //如果写锁可重入次数超过最大次数(65535),则抛异常
74                if (w + exclusiveCount(acquires) > MAX_COUNT)
75                    throw new Error("Maximum lock count exceeded");
76                //到这里说明该线程是重入写锁,更新重入写锁的计数(+1),返回true
77                // Reentrant acquire
78                setState(c + acquires);
79                return true;
80            }
81            //如果读写锁状态为0,说明读锁和写锁都没有被获取,会走下面两个分支:
82            //如果要阻塞或者执行CAS操作更新读写锁的状态失败,则返回false
83            //如果不需要阻塞且CAS操作成功,则当前线程成功拿到锁,设置锁的owner为当前线程,返回true
84            if (writerShouldBlock() ||
85                !compareAndSetState(c, c + acquires))
86                return false;
87            setExclusiveOwnerThread(current);
88            return true;
89        }

释放写锁源码:

 1/*
 2  * Note that tryRelease and tryAcquire can be called by
 3  * Conditions. So it is possible that their arguments contain
 4  * both read and write holds that are all released during a
 5  * condition wait and re-established in tryAcquire.
 6  */
 7 protected final boolean tryRelease(int releases) {
 8     //若锁的持有者不是当前线程,抛出异常
 9     if (!isHeldExclusively())
10         throw new IllegalMonitorStateException();
11     //写锁的可重入计数减掉releases个
12     int nextc = getState() - releases;
13     //如果写锁重入计数为0了,则说明写锁被释放了
14     boolean free = exclusiveCount(nextc) == 0;
15     if (free)
16        //若写锁被释放,则将锁的持有者设置为null,进行GC
17        setExclusiveOwnerThread(null);
18     //更新写锁的重入计数
19     setState(nextc);
20     return free;
21 }

获取读锁源码:

  1/**
  2         * 获取读锁
  3         * Acquires the read lock.
  4         * 如果写锁未被其他线程持有,执行CAS操作更新status值,获取读锁后立即返回
  5         * <p>Acquires the read lock if the write lock is not held by
  6         * another thread and returns immediately.
  7         *
  8         * 如果写锁被其他线程持有,那么停止该线程的CPU调度并进入休眠状态,直到该读锁被释放
  9         * <p>If the write lock is held by another thread then
 10         * the current thread becomes disabled for thread scheduling
 11         * purposes and lies dormant until the read lock has been acquired.
 12         */
 13        public void lock() {
 14            sync.acquireShared(1);
 15        }
 16   /**
 17     * 该方法为以共享模式获取读锁,忽略中断
 18     * 如果调用一次该“tryAcquireShared”方法更新status成功,则直接返回,代表抢锁成功
 19     * 否则,将会进入同步队列等待,不断执行“tryAcquireShared”方法尝试CAS更新status状态,直到成功抢到锁
 20     * 其中“tryAcquireShared”方法在NonfairSync(公平锁)中和FairSync(非公平锁)中都有各自的实现
 21     * (看这注释是不是和写锁很对称)
 22     * Acquires in shared mode, ignoring interrupts.  Implemented by
 23     * first invoking at least once {@link #tryAcquireShared},
 24     * returning on success.  Otherwise the thread is queued, possibly
 25     * repeatedly blocking and unblocking, invoking {@link
 26     * #tryAcquireShared} until success.
 27     *
 28     * @param arg the acquire argument.  This value is conveyed to
 29     *        {@link #tryAcquireShared} but is otherwise uninterpreted
 30     *        and can represent anything you like.
 31     */
 32    public final void acquireShared(int arg) {
 33        if (tryAcquireShared(arg) < 0)
 34            doAcquireShared(arg);
 35    }
 36    protected final int tryAcquireShared(int unused) {
 37            /*
 38             * Walkthrough:
 39             * 1、如果已经有其他线程获取到了写锁,根据“读写互斥”原则,抢锁失败,返回-1
 40             * 1.If write lock held by another thread, fail.
 41             * 2、如果该线程本身持有写锁,那么看一下是否要readerShouldBlock,如果不需要阻塞,
 42             *    则执行CAS操作更新state和重入计数。
 43             *    这里要注意的是,上面的步骤不检查是否可重入(因为读锁属于共享锁,天生支持可重入)
 44             * 2. Otherwise, this thread is eligible for
 45             *    lock wrt state, so ask if it should block
 46             *    because of queue policy. If not, try
 47             *    to grant by CASing state and updating count.
 48             *    Note that step does not check for reentrant
 49             *    acquires, which is postponed to full version
 50             *    to avoid having to check hold count in
 51             *    the more typical non-reentrant case.
 52             * 3、如果因为CAS更新status失败或者重入计数超过最大值导致步骤2执行失败
 53             *    那就进入到fullTryAcquireShared方法进行死循环,直到抢锁成功
 54             * 3. If step 2 fails either because thread
 55             *    apparently not eligible or CAS fails or count
 56             *    saturated, chain to version with full retry loop.
 57             */
 58
 59            //当前尝试获取读锁的线程
 60            Thread current = Thread.currentThread();
 61            //获取该读写锁状态
 62            int c = getState();
 63            //如果有线程获取到了写锁 ,且获取写锁的不是当前线程则返回失败
 64            if (exclusiveCount(c) != 0 &&
 65                getExclusiveOwnerThread() != current)
 66                return -1;
 67            //获取读锁的重入计数
 68            int r = sharedCount(c);
 69            //如果读线程不应该被阻塞,且重入计数小于最大值,且CAS执行读锁重入计数+1成功,则执行线程重入的计数加1操作,返回成功
 70            if (!readerShouldBlock() &&
 71                r < MAX_COUNT &&
 72                compareAndSetState(c, c + SHARED_UNIT)) {
 73                //如果还未有线程获取到读锁,则将firstReader设置为当前线程,firstReaderHoldCount设置为1
 74                if (r == 0) {
 75                    firstReader = current;
 76                    firstReaderHoldCount = 1;
 77                } else if (firstReader == current) {
 78                    //如果firstReader是当前线程,则将firstReader的重入计数变量firstReaderHoldCount加1
 79                    firstReaderHoldCount++;
 80                } else {
 81                    //否则说明有至少两个线程共享读锁,获取共享锁重入计数器HoldCounter
 82                    //从HoldCounter中拿到当前线程的线程变量cachedHoldCounter,将此线程的重入计数count加1
 83                    HoldCounter rh = cachedHoldCounter;
 84                    if (rh == null || rh.tid != getThreadId(current))
 85                        cachedHoldCounter = rh = readHolds.get();
 86                    else if (rh.count == 0)
 87                        readHolds.set(rh);
 88                    rh.count++;
 89                }
 90                return 1;
 91            }
 92            //如果上面的if条件有一个都不满足,则进入到这个方法里进行死循环重新获取
 93            return fullTryAcquireShared(current);
 94        }
 95        /**
 96         * 用于处理CAS操作state失败和tryAcquireShared中未执行获取可重入锁动作的full方法(补偿方法?)
 97         * Full version of acquire for reads, that handles CAS misses
 98         * and reentrant reads not dealt with in tryAcquireShared.
 99         */
100        final int fullTryAcquireShared(Thread current) {
101            /*
102             * 此代码与tryAcquireShared中的代码有部分相似的地方,
103             * 但总体上更简单,因为不会使tryAcquireShared与重试和延迟读取保持计数之间的复杂判断
104             * This code is in part redundant with that in
105             * tryAcquireShared but is simpler overall by not
106             * complicating tryAcquireShared with interactions between
107             * retries and lazily reading hold counts.
108             */
109            HoldCounter rh = null;
110            //死循环
111            for (;;) {
112                //获取读写锁状态
113                int c = getState();
114                //如果有线程获取到了写锁
115                if (exclusiveCount(c) != 0) {
116                    //如果获取写锁的线程不是当前线程,返回失败
117                    if (getExclusiveOwnerThread() != current)
118                        return -1;
119                    // else we hold the exclusive lock; blocking here
120                    // would cause deadlock.
121                } else if (readerShouldBlock()) {//如果没有线程获取到写锁,且读线程要阻塞
122                    // Make sure we're not acquiring read lock reentrantly
123                    //如果当前线程为第一个获取到读锁的线程
124                    if (firstReader == current) {
125                        // assert firstReaderHoldCount > 0;
126                    } else { //如果当前线程不是第一个获取到读锁的线程(也就是说至少有有一个线程获取到了读锁)
127                        //
128                        if (rh == null) {
129                            rh = cachedHoldCounter;
130                            if (rh == null || rh.tid != getThreadId(current)) {
131                                rh = readHolds.get();
132                                if (rh.count == 0)
133                                    readHolds.remove();
134                            }
135                        }
136                        if (rh.count == 0)
137                            return -1;
138                    }
139                }
140                /**
141                 *下面是既没有线程获取写锁,当前线程又不需要阻塞的情况
142                 */
143                //重入次数等于最大重入次数,抛异常
144                if (sharedCount(c) == MAX_COUNT)
145                    throw new Error("Maximum lock count exceeded");
146                //如果执行CAS操作成功将读写锁的重入计数加1,则对当前持有这个共享读锁的线程的重入计数加1,然后返回成功
147                if (compareAndSetState(c, c + SHARED_UNIT)) {
148                    if (sharedCount(c) == 0) {
149                        firstReader = current;
150                        firstReaderHoldCount = 1;
151                    } else if (firstReader == current) {
152                        firstReaderHoldCount++;
153                    } else {
154                        if (rh == null)
155                            rh = cachedHoldCounter;
156                        if (rh == null || rh.tid != getThreadId(current))
157                            rh = readHolds.get();
158                        else if (rh.count == 0)
159                            readHolds.set(rh);
160                        rh.count++;
161                        cachedHoldCounter = rh; // cache for release
162                    }
163                    return 1;
164                }
165            }
166        }
167
168```java
169
170释放读锁源码:
171
172```java
173/**
174  * Releases in shared mode.  Implemented by unblocking one or more
175  * threads if {@link #tryReleaseShared} returns true.
176  *
177  * @param arg the release argument.  This value is conveyed to
178  *        {@link #tryReleaseShared} but is otherwise uninterpreted
179  *        and can represent anything you like.
180  * @return the value returned from {@link #tryReleaseShared}
181  */
182public final boolean releaseShared(int arg) {
183    if (tryReleaseShared(arg)) {//尝试释放一次共享锁计数
184        doReleaseShared();//真正释放锁
185        return true;
186    }
187        return false;
188}
189/**
190 *此方法表示读锁线程释放锁。
191 *首先判断当前线程是否为第一个读线程firstReader,
192 *若是,则判断第一个读线程占有的资源数firstReaderHoldCount是否为1,
193  若是,则设置第一个读线程firstReader为空,否则,将第一个读线程占有的资源数firstReaderHoldCount减1;
194  若当前线程不是第一个读线程,
195  那么首先会获取缓存计数器(上一个读锁线程对应的计数器 ),
196  若计数器为空或者tid不等于当前线程的tid值,则获取当前线程的计数器,
197  如果计数器的计数count小于等于1,则移除当前线程对应的计数器,
198  如果计数器的计数count小于等于0,则抛出异常,之后再减少计数即可。
199  无论何种情况,都会进入死循环,该循环可以确保成功设置状态state
200 */
201protected final boolean tryReleaseShared(int unused) {
202      // 获取当前线程
203      Thread current = Thread.currentThread();
204      if (firstReader == current) { // 当前线程为第一个读线程
205          // assert firstReaderHoldCount > 0;
206         if (firstReaderHoldCount == 1) // 读线程占用的资源数为1
207              firstReader = null;
208          else // 减少占用的资源
209              firstReaderHoldCount--;
210     } else { // 当前线程不为第一个读线程
211         // 获取缓存的计数器
212         HoldCounter rh = cachedHoldCounter;
213         if (rh == null || rh.tid != getThreadId(current)) // 计数器为空或者计数器的tid不为当前正在运行的线程的tid
214             // 获取当前线程对应的计数器
215             rh = readHolds.get();
216         // 获取计数
217         int count = rh.count;
218         if (count <= 1) { // 计数小于等于1
219             // 移除
220             readHolds.remove();
221             if (count <= 0) // 计数小于等于0,抛出异常
222                 throw unmatchedUnlockException();
223         }
224         // 减少计数
225         --rh.count;
226     }
227     for (;;) { // 死循环
228         // 获取状态
229         int c = getState();
230         // 获取状态
231         int nextc = c - SHARED_UNIT;
232         if (compareAndSetState(c, nextc)) // 比较并进行设置
233             // Releasing the read lock has no effect on readers,
234             // but it may allow waiting writers to proceed if
235             // both read and write locks are now free.
236             return nextc == 0;
237     }
238 }
239 /**真正释放锁
240  * Release action for shared mode -- signals successor and ensures
241  * propagation. (Note: For exclusive mode, release just amounts
242  * to calling unparkSuccessor of head if it needs signal.)
243  */
244private void doReleaseShared() {
245        /*
246         * Ensure that a release propagates, even if there are other
247         * in-progress acquires/releases.  This proceeds in the usual
248         * way of trying to unparkSuccessor of head if it needs
249         * signal. But if it does not, status is set to PROPAGATE to
250         * ensure that upon release, propagation continues.
251         * Additionally, we must loop in case a new node is added
252         * while we are doing this. Also, unlike other uses of
253         * unparkSuccessor, we need to know if CAS to reset status
254         * fails, if so rechecking.
255         */
256        for (;;) {
257            Node h = head;
258            if (h != null && h != tail) {
259                int ws = h.waitStatus;
260                if (ws == Node.SIGNAL) {
261                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
262                        continue;            // loop to recheck cases
263                    unparkSuccessor(h);
264                }
265                else if (ws == 0 &&
266                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
267                    continue;                // loop on failed CAS
268            }
269            if (h == head)                   // loop if head changed
270                break;
271        }
272    }
273
274```java
275
276**对同一个线程来说(可重入),在线程持有读锁的情况下,该线程不能取得写锁****(因为获取写锁的时候,如果发现当前的读锁被占用,就马上获取失败,不管读锁是不是被当前线程持有)**
277
278**对同一个线程来说(可重入),在线程持有写锁的情况下,该线程可以继续获取读锁****(获取读锁时如果发现写锁被占用,只有写锁没有被当前线程占用的情况才会获取失败)。**
279
280** 读锁使用的是共享锁,多个读锁可以一起获取锁,互相不会影响,即读读不互斥;**
281
282** 读写、写读和写写是会互斥的(****多线程情况****),前者占有着锁,后者需要进入AQS队列中排队**
283
284** 多个连续的读线程是一个接着一个被唤醒的,而不是一次性唤醒所有读线程;**
285
286** 只有多个读锁都完全释放了才会唤醒下一个写线程;**
287
288** 只有写锁完全释放了才会唤醒下一个等待者,这个等待者有可能是读线程,也可能是写线程;**
289
290** 读写所允许同一时刻被多个读线程访问,但是在写线程访问时,所有的读线程和其他的写线程都会被阻塞。**
291
292** 读写锁保证了写操作对后续的读操作的可见性**
293
294** 锁降级:遵循获取写锁,获取读锁再释放写锁的次序,写锁能够降级为读锁**
295
296锁降级指的是写锁降级成为读锁。如果当前线程拥有写锁,然后将其释放,最后再获取读锁,这种分段完成的过程不能称之为锁降级。锁降级是指把持住(当前拥有的)写锁,再获取到读锁,随后释放(先前拥有的)写锁的过程。
297
298```cs
299public void processData() {
300        readLock.lock();
301        if (!update) {
302            // 必须先释放读锁
303            readLock.unlock();
304            // 锁降级从写锁获取到开始
305            writeLock.lock();
306            try {
307                if (!update) {
308                    // 准备数据的流程(略)
309                    update = true;
310                }
311                readLock.lock();
312            } finally {
313                writeLock.unlock();
314            }// 锁降级完成,写锁降级为读锁
315        }
316        try {// 使用数据的流程(略)
317        } finally {
318            readLock.unlock();
319        }
320    }

参考

Image

关注公众号 获取更多精彩内容

位旅人路过 次翻阅 初次见面