JDK8 JUC阅读(4)

并发List

Posted by Jqy on January 11, 2020

JDK提供的并发安全队列大体可以分为两类,基于锁的阻塞队列和基于CAS的非阻塞队列。

1.ConcurrentLinkedQueue

内部队列采用单向链表,两个volatile类型的Node指向了头尾节点。

offer

末尾添加元素,由于是无界队列,会始终返回true,最终调用的是linkLast

private void linkLast(E e) {
        checkNotNull(e);
        final Node<E> newNode = new Node<E>(e);

        restartFromTail:
        for (;;)
            for (Node<E> t = tail, p = t, q;;) {
                if ((q = p.next) != null &&
                    (q = (p = q).next) != null)
                    // Check for tail updates every other hop.
                    // If p == q, we are sure to follow tail instead.
                    p = (t != (t = tail)) ? t : q;
                else if (p.prev == p) // NEXT_TERMINATOR
                    continue restartFromTail;
                else {
                    //q==null说明p是尾结点,执行插入
                    newNode.lazySetPrev(p); // CAS piggyback
                    if (p.casNext(null, newNode)) {
                        // Successful CAS is the linearization point
                        // for e to become an element of this deque,
                        // and for newNode to become "live".
                        if (p != t) // hop two nodes at a time
                            casTail(t, newNode);  // Failure is OK.
                        return;
                    }
                    // Lost CAS race to another thread; re-read next
                }
            }
    }