java并发编程---ReentrantLock公平锁实现原理

java并发编程—ReentrantLock公平锁实现原理

如果一个线程组里,能保证每个线程都能拿到锁,那么这个锁就是公平锁。相反,如果保证不了每个线程都能拿到锁,也就是存在有线程饿死,那么这个锁就是非公平锁。

先看非公平锁

在这里插入图片描述

static final class NonfairSync extends Sync {
        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }
    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

在这里插入图片描述

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }

非公平锁最后调用nonfairTryAcquire方法

        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            //如果还没有获得锁
            if (c == 0) {
            	//尝试用cas获得,这里体现了非公平性:不去检查AQS队列
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            //如果已经获得了锁,线程还是当前线程,表示发生`static final class FairSync extends Sync {了锁重入
            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;
        }

公平锁的实现

static final class FairSync extends Sync {
final void lock() {
            acquire(1);
        }
    public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

在这里插入图片描述

		//与非公平锁主要区别在于tryAcquire方法的实现
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
            	//先检查AQS队列中是否有前驱节点,没有才去竞争
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }

这里hasQueuedPredecessors()不成立才会去调用compareAndSetState,去抢线程。如果hasQueuedPredecessors()成立,相当于队列中有其他的线程,下面的compareAndSetState就不会执行。
注意&& 是短路运算。

	//判断队列中是否有一个前驱的节点
    public final boolean hasQueuedPredecessors() {
        Node t = tail; // Read fields in reverse initialization order
        Node h = head;
        Node s;
        // h != t 时表示队列中有Node
        return h != t &&
        	//情况一,(s = h.next) == null 表示队列中还没有老二
        	//情况二,队列中老二线程不是此线程        	
            ((s = h.next) == null || s.thread != Thread.currentThread());						
    }

头不等于尾,队列中有节点。
队列中还没有老二,队列中老二线程不是此线程,则返回true
这说明队列中有优先级比你高的线程在等待,则不会往下去执行竞争锁compareAndSetState(0, acquires))

参考资料

http://www.codeceo.com/article/reentrantlock-learn.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值