AQS学习

文章目的

此文章主要是为了通过简单介绍AQS的基本原理,来学习JAVA中一些锁的实现,解释可重入锁/不可重入锁,独占锁/非独占锁,公平锁/非公平锁的实现原理。

初识AQS

获取锁

基本的获取锁的方法调用流程
![AOS基本调用流程图](https://img-blog.csdnimg.cn/20190108175239975.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NDM2NjQzOQ==,size_16,color_FFFFFF,t_7入口在这里

public final void acquire(int arg) {
    // 由子类重写的方法先取尝试一下能不能获取到锁
    if (!tryAcquire(arg) &&
    // 如果没有获取到锁则addWaiter再acquireQueued
        acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
        selfInterrupt();
}
addWaiter加入队列
/**
 * Creates and enqueues node for current thread and given mode.
 *
 * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
 * @return the new node
 */
 // 根据当前线程创建一个node并且入队,先尝试一次,如果失败就用enq方法来重试
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;
}
/**
 * Inserts node into queue, initializing if necessary. See picture above.
 * @param node the node to insert
 * @return node's predecessor
 */
private Node enq(final Node node) {
    // 循环重试插入
    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;
            }
        }
    }
}
最后是acquireQueued, 一个线程是继续执行还是阻塞就决定在这里了:
    /**
     * Acquires in exclusive uninterruptible mode for thread already in
     * queue. Used by condition wait methods as well as acquire.
     *
     * @param node the node
     * @param arg the acquire argument
     * @return {@code true} if interrupted while waiting
     */
     // 很多地方会调用,包括condition和上面的acquire.
    final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            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);
        }
    }
shouldParkAfterFailedAcquire阻塞线程,设置父节点状态SIGNAL
    /**
     * Checks and updates status for a node that failed to acquire.
     * Returns true if thread should block. This is the main signal
     * control in all acquire loops.  Requires that pred == node.prev.
     *
     * @param pred node's predecessor holding status
     * @param node the node
     * @return {@code true} if thread should block
     */
     // 这个方法需要由调用者来循环重试,值到将前一个节点的状态改为-1为止
    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        int ws = pred.waitStatus;
        // 如果前面一个节点的状态是-1则block,表名是正常的可以被唤醒
        if (ws == Node.SIGNAL)
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
        //如果不是-1,大于0,说明上一级节点状态是1,异常的,需要过滤掉所有的上一级节点,一致找到上一级节点小于0的,认这个小于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;
            // 这里代表为-2,或者-3,或者0
        } 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.
             */
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

这里借用一下别人的说法"waitStatus 中 SIGNAL(-1) 状态的意思,Doug Lea 注释的是:代表后继节点需要被唤醒。也就是说这个 waitStatus 其实代表的不是自己的状态,而是后继节点的状态,我们知道,每个 node 在入队的时候,都会把前驱节点的状态改为 SIGNAL,然后阻塞,等待被前驱唤醒"

 *   SIGNAL:     The successor of this node is (or will soon be)
 *               blocked (via park), so the current node must
 *               unpark its successor when it releases or
 *               cancels. To avoid races, acquire methods must
 *               first indicate they need a signal,
 *               then retry the atomic acquire, and then,
 *               on failure, block.
 注释:
successor代表此节点的下一个节点(继承者)。
我这个node状态为-1代表我的继承者是或者将要是阻塞的,所以当我这个node释放了或者取消的时候,我必须唤醒我的继承者。为了避免冲突。。。这一段指的应该就是shouldParkAfterFailedAcquire方法吧。

释放锁

从获取锁的过程中我们了解到,由于把所有等待获取锁的线程都封装成node放在阻塞队列里,那释放锁的时候肯定和这个阻塞队列有关,以及和waitstatus状态有关。

释放锁的入口
    /**
     * Releases in exclusive mode.  Implemented by unblocking one or
     * more threads if {@link #tryRelease} returns true.
     * This method can be used to implement method {@link Lock#unlock}.
     *
     * @param arg the release argument.  This value is conveyed to
     *        {@link #tryRelease} but is otherwise uninterpreted and
     *        can represent anything you like.
     * @return the value returned from {@link #tryRelease}
     */
    public final boolean release(int arg) {
    // 子类需要实现的方法,如果尝试释放锁成功后,就要使用unparkSuccessor来唤醒继承者(后面的那个节点)
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }
修改锁的状态为已经释放

在看unparkSuccessor之前我们先看一下ReentrantLock中tryRelease的实现。所以这里我们看到ReentrantLock并不会关心如何唤醒其他线程,只需要关心它目前处于什么状态时即可表示当前线程已经完全将锁释放掉。

protected final boolean tryRelease(int releases) {
			// 由于是可重入锁,所以如果锁了多次,则要释放多次
           int c = getState() - releases;
           if (Thread.currentThread() != getExclusiveOwnerThread())
               throw new IllegalMonitorStateException();
           boolean free = false;
           // 只有当status释放后为0的时候才会返回true
           if (c == 0) {
               free = true;
               setExclusiveOwnerThread(null);
           }
           setState(c);
           return free;
       }
唤醒等待锁的阻塞线程

接下来我们看一下AQS是如何唤醒线程的,在unparkSuccessor方法中。

    /**
   * Wakes up node's successor, if one exists.
   *
   * @param node the node
   */
  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;
      //从上文的调用来看我们知道这里的node节点是head头节点,当小于0 的时候会将他设置为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;
          //这里是从尾节点向前找到第一个有效节点,为什么要从尾节点找而不是当前节点的下一个,这里要看addWaiter方法的代码。
          for (Node t = tail; t != null && t != node; t = t.prev)
              if (t.waitStatus <= 0)
                  s = t;
      }
      //如果下一个节点不为空并且waitstatus是有效的则唤醒改线程。
      if (s != null)
          LockSupport.unpark(s.thread);
  }

小结

AQS帮助实现了一个基于链表的数据结构,在获取锁和释放锁的时候只需要实现相关的tryXXX方法,不需要关心线程实际是如何阻塞和唤醒的,通过对它暴露出的一些方法进行定制化来实现相关逻辑。获取锁的核心逻辑在于acquire方法,这个方法中暴露了tryAcquire来给子类进行定制化操作。释放锁的核心逻辑在于release方法,暴露了tryRelease来给子类进行定制化操作。

AQS实现公平/非公平锁

ReentrantLock实现的公平锁

ReentrantLock内部实现了静态内部类Sync,FairSync(公平锁)和NonfairSync(非公平锁),FairSync继承了Sync,Sync继承了AQS。
我们先回忆一下AQS这段代码,尝试获取不到锁时就入队等待,获取到锁就占有锁。

 public final void acquire(int arg) {
      if (!tryAcquire(arg) &&
          acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
          selfInterrupt();
  }

现在看一下FairSync的实现方式。


static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        final void lock() {
            acquire(1);
        }

        /**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            // 为0代表当前锁是空闲的,可以被获取到
            if (c == 0) {
            	//判断是否有其他线程在队列中阻塞等待被唤醒
                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;
        }
    }

我们可以看到对于公平锁来说,是否能拿到锁有两道关卡,第一道是当前锁是否被占用。第二道是当前是否有其他线程在等待获取锁。公平锁是礼貌的,当它发现锁可用的时候也不会直接拿来用,而是先看看有没有人正在排队,有人排队则礼貌的排队等待。

非公平锁

 static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;

        /**
         * Performs lock.  Try immediate barge, backing up to normal
         * acquire on failure.
         */
        final void lock() {
        	//这里很暴力的直接尝试修改锁的状态,如果修改成功则直接获取到锁了
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            //修改失败后才考虑取获取锁
            else
                acquire(1);
        }

        protected final boolean tryAcquire(int acquires) {
            return nonfairTryAcquire(acquires);
        }
    }
    **
         * Performs non-fair tryLock.  tryAcquire is implemented in
         * subclasses, but both need nonfair try for trylock method.
         */
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            int c = getState();
            if (c == 0) {
            	// 这里和公平锁的区别是它根本不管队列里有没有人在等待
                if (compareAndSetState(0, acquires)) {
                    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;
        }

所以这里可以看到这里非公平锁是很不礼貌的,它来了就直接拿锁,发现锁被占用后才去排队。

小结

通过对比可知ReentrantLock实现公平和非公平锁时采用的区别主要在于是否判断有线程正在排队等待。非公平每个新的线程想获取锁都可能立即拿到锁,而公平锁的话一定是会排队的。所以公平锁的吞吐量是不如非公平锁的,但是非公平锁会导致饥饿现象。

参考文章

https://javadoop.com/post/AbstractQueuedSynchronizer

https://tech.meituan.com/Java_Lock.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值