同步队列

 

一  AQS同步队列实现分析

AQS是一个

1  同步队列

AQS是通过一个内部的FIFO的同步队列来管理同步状态,当线程获取锁失败的时候,当前想线程以及当前线程的状态等信息,会被构造成一个节点加入到同步队列的尾部,然后阻塞当前线程。那么这个节点保存哪些信息呢?

当前线程的引用、等待状态以及当前节点的前驱节点和后继节点。

同步器中存在两种引用:指向首节点的引用和指向尾节点的引用.

首节点是成功获取同步状态的节点,当首节点释放同步状态的时候,将会唤醒后继节点,当后继节点成功获取同步状态以后会将自己设置为首节点。关于首节点和尾节点的设置有一下两点需要说下:

a.首节点是成功获取同步状态的节点,因为只有一个线程可以成功获取同步状态,因此设置首节点不需要CAS设置。

b.一般情况下,会有多个获取锁失败,而获取锁失败的节点会被设置为尾节点,这里线程是通过CAS设置尾节点的,同一时刻必须保证只能一个线程加入到队列尾部,将尾节点的引用指向当前线程的节点.当成功设置为尾节点以后,只有正式设置成功以后,该节点才能与之前的尾节点建立连接。

 

2 独占式获取锁和释放锁

关于独占式获取锁,.首先调用acquire(int arg)方法。

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

线程调用tryAcquire方法去获取同步状态,tryAcquire方法是需要子类自己实现的,当获取同步状态失败以后,调用addWaiter(Node.EXCLUSIVE)方法将当前线程创建为节点加入到队列尾部

 /**
     * Creates and enqueues node for current thread and given mode.
     *
     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
     * @return the new node
     */
    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;
            //CAS设置为尾节点
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        //当同步队列为空的时候,调用enq()方法,无限循环,该方法通过CAS设置头节点初始化同步队列, 然后在将自己设置为尾节点.成功设置尾节点后,再和之前的尾节点建立连接
        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方法,

线程调用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
     */
    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方法,获取其前置节点的状态,获取到其前置节点的状态以后,会进行如下判断:

1 如果其前置节点的状态是SIGNAL,直接返回true;

2 如果其前置节点的状态>0,也就是处于CANCELLED状态,取消状态,就跳过其前置节点,在往前寻找状态不为取消状态的节点作为其前置节点.

3 如果其状态,小于0,但不是SIGNAL状态,那么直接CAS设置其前置节点的状态为SIGNAL

  当成功将其前置节点设置为SIGNAL后,调用parkAndCheckInterrupt将当前线程挂起。

 

shouldParkAfterFailedAcquire方法检查且更新一个获取锁失败的节点状态,如果线程应该阻塞,那么返回true,
   /**
     * 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
     */
    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        //获取前置节点的等待状态
        int ws = pred.waitStatus;
        //如果前置节点的状态是后继节点需要被唤醒
        if (ws == Node.SIGNAL)
            /*
             * This node has already set status asking a release
             * to signal it, so it can safely park.
             */
            return true;
        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.
             */
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

释放同步状态调用的是release()方法,看代码:

release(int args)方法用于在独占模式下释放锁,用于被非阻塞的线程调用,可以去实现Lock接口下的unlock方法

如果线程释放同步状态成功,且头结点不为空,唤醒后继线程,返回true,失败返回false

   /**
     * 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) {
        if (tryRelease(arg)) {
            Node h = head;
            if (h != null && h.waitStatus != 0)
                unparkSuccessor(h);
            return true;
        }
        return false;
    }

 

3 共享式获取锁和释放锁

 

 

 

展开阅读全文

没有更多推荐了,返回首页