基于AQS的独占锁实现逻辑

ReentrantLock

加锁逻辑

独占锁的正常使用方式,先从加锁逻辑开始。

	Lock lock = new ReentrantLock();
    
    public void test() {
        try{
            lock.lock();
            //todo
        }finally {
            lock.unlock();
        }
    }

ReentrantLock分公平锁和非公平锁,公平锁指抢锁的线程进来先入队列排队,按照FIFO的方式获取锁。而非公平锁指线程开始可以插队尝试获取锁,如果获取失败,才入队列排队,接着按照FIFO的方式获取锁。其实非公平锁的后一部分逻辑和公平锁一样,下面以非公平锁分析。

        final void lock() {
        	//进来首先使用CAS尝试获取锁
            if (compareAndSetState(0, 1))
            	//获取锁成功,设置当前独占锁线程为本线程
                setExclusiveOwnerThread(Thread.currentThread());
            else
            	//进到这里说明第一次尝试获取锁失败
                acquire(1);
        }

下面接着看acquire(1):

    public final void acquire(int arg) {
    	//tryAcquire(arg)是子类的实现方法,这里用了模板方法设计模式
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
    }

下面把acquire(int arg)下的几个方法拆开来看:

        protected final boolean tryAcquire(int acquires) {
        	//非公平锁尝试申请获取锁
            return nonfairTryAcquire(acquires);
        }
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            //如果c==0,说明没有线程持有锁,接下来使用CAS尝试获取锁
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            //如果c!=0,判断持有锁的线程是否是当前线程,这里支持锁的可重入性
            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;
        }

分析完了acquire(1),接下来分析addWaiter(Node.EXCLUSIVE),走到这里说明锁被其他线程拿去了:

    private Node addWaiter(Node mode) {
    	//为当前线程新建一个节点,准备加入到尾节点
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        if (pred != null) {
        	//设置新节点的前驱节点
            node.prev = pred;
            //把新节点添加到原来的尾节点后,成为新的尾节点
            if (compareAndSetTail(pred, node)) {
            	//双向链表形成
                pred.next = node;
                return node;
            }
        }
        //如果走到这里,说明更新尾节点失败,进入自旋,不断尝试将自己添加到尾节点
        enq(node);
        return node;
    }
    private Node enq(final Node node) {
    	//for循环自旋操作,如果更新失败,会再次尝试更新,直到成功为止
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                //重新尝试将新节点添加到尾节点,直到成功为止
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }

这时候已经将新节点添加到队列尾部了,接下来往下看:

	//node就是新加进去的尾节点
    final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            //for循环自旋操作
            for (;;) {
                final Node p = node.predecessor();
                //如果新节点的前驱节点是头节点,并且新节点再次尝试获取锁成功了,说明头节点释放了锁,头节点出链表,新节点成为新的头节点
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
        	//如果请求抛出了异常,取消当前线程获取锁的权力
            if (failed)
                cancelAcquire(node);
        }
    }

下面是挂起逻辑:

    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;
        //如果前驱节点是SINGNAL,当前线程可以安心睡大觉了(挂起),等待前驱节点唤醒即可
        if (ws == Node.SIGNAL)
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
         //如果前驱节点被取消(waitStatus>0表示无效节点),会一直往前找有效的节点,把新节点加到后面
        if (ws > 0) {
            /*
             * Predecessor was cancelled. Skip over predecessors and
             * indicate retry.
             */
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            /*
             * waitStatus must be 0 or PROPAGATE.  Indicate that we
             * need a signal, but don't park yet.  Caller will need to
             * retry to make sure it cannot acquire before parking.
             */
             //表示ws<0且ws !=Node.SIGNAL,修改前驱节点的状态为Node.SIGNAL,返回false后进入acquireQueued(final Node node, int arg)的下一次自旋,然后返回true
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        //返回false后会进入for(;;)的下一次自旋
        return false;
    }

在上述代码中返回true后,下面是真正的挂起逻辑,将当前线程挂起,避免无休止的自旋消耗CPU资源。注意,后面将唤醒已挂起的线程的时候,从这里开始唤醒,成功获取锁,走完lock.lock()方法,进入业务代码:

    private final boolean parkAndCheckInterrupt() {
        LockSupport.park(this);
        return Thread.interrupted();
    }

释放锁逻辑

释放锁的逻辑,无论公平锁还是非公平锁都是一样的。

    public void unlock() {
        sync.release(1);
    }
	//释放锁
    public final boolean release(int arg) {
    	//tryRelease(arg) 返回true,表示成功释放了锁
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
            	//头节点其实就是刚释放了锁的线程,自己释放了锁后,唤醒后继节点
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

尝试释放锁:

        protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            //先判断当前请求释放锁的线程是否是当前持有锁的线程
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            //c == 0 说明将进入无锁状态。因我如果是可重入锁,进入一次state+1,同理,释放锁一次state-1,直到state == 0说明完全释放锁
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            //标志是否释放了锁
            return free;
        }

唤醒后继节点:

    private void unparkSuccessor(Node node) {
        /*
         * If status is negative (i.e., possibly needing signal) try
         * to clear in anticipation of signalling.  It is OK if this
         * fails or if status is changed by waiting thread.
         */
        int ws = node.waitStatus;
        //更新当前节点的状态为0
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);

        /*
         * Thread to unpark is held in successor, which is normally
         * just the next node.  But if cancelled or apparently null,
         * traverse backwards from tail to find the actual
         * non-cancelled successor.
         */
         //获取后继节点
        Node s = node.next;
        if (s == null || s.waitStatus > 0) {
            s = null;
            //如果后继节点为空或者后继节点的状态为cancel,从尾节点一直往前找,去除掉链表中所有不满足要求的节点
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        //唤醒线程
        if (s != null)
            LockSupport.unpark(s.thread);
    }

总结

在获取同步状态时,同步器维护一个同步队列,获取状态失败的线程都会被加入到队列中并在队列中进行自旋;移出队列(或停止自旋)的条件是前驱节点为头节点且成功获取了同步状态。在释放同步状态时,同步器调用tryRelease(int arg)方法释放同步状态,然后唤醒head指向节点的后继节点。

节点加入到链表尾部和从链表移出示意图
通过上面的源码分析,结合下图理解。

节点加入到链表尾部:
加入到链表尾部
节点从链表移除:
节点从链表移除
独占式同步状态获取与释放流程图:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值