Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

从ReentrantLock的实现看AQS的原理及应用中有一副以非公平锁方式加锁的图解误差? #1761

Closed
xiaopujun opened this issue Jun 29, 2022 · 1 comment
Labels
perfect content improve the content

Comments

@xiaopujun
Copy link

问题描述:
1、并发编程--> 重要知识点-->从ReentrantLock的实现看AQS的原理及应用中有一副以非公平锁方式加锁的图解
2、其中如下部分的流程图是否与源码有出入呢?
image
3、源码jdk1.8如下

final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();//获取当前线程
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {//CAS抢锁
                    setExclusiveOwnerThread(current);//设置当前线程为独占线程
                    return true;//抢锁成功
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
@Snailclimb
Copy link
Owner

问题描述: 1、并发编程--> 重要知识点-->从ReentrantLock的实现看AQS的原理及应用中有一副以非公平锁方式加锁的图解 2、其中如下部分的流程图是否与源码有出入呢? image 3、源码jdk1.8如下

final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();//获取当前线程
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {//CAS抢锁
                    setExclusiveOwnerThread(current);//设置当前线程为独占线程
                    return true;//抢锁成功
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

是的,这应该是图中的一处笔误。2.2流程图中,(AQS)CAS修改共享资源 state 成功之后应该是获取锁成功(非公平锁)。

@Snailclimb Snailclimb added the perfect content improve the content label Jul 25, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
perfect content improve the content
Projects
None yet
Development

No branches or pull requests

2 participants