publicConcurrentLinkedDeque() { head = tail = newNode<E>(); }
publicConcurrentLinkedDeque(Collection<? extends E> c) { // Copy c into a private chain of Nodes Node<E> h = null, t = null; for (E e : c) { Node<E> newNode = newNode(Objects.requireNonNull(e)); if (h == null) h = t = newNode; else { NEXT.set(t, newNode); PREV.set(newNode, t); t = newNode; } } initHeadTail(h, t); }
privatevoidlinkFirst(E e) { // 创建当前节点 final Node<E> newNode = newNode(Objects.requireNonNull(e));
restartFromHead: for (;;) for (Node<E> h = head, p = h, q;;) { // 如果节点的前置节点不为空,更新p节点 if ((q = p.prev) != null && (q = (p = q).prev) != null) // Check for head updates every other hop. // If p == q, we are sure to follow head instead. p = (h != (h = head)) ? h : q; // p节点出队了重新从头开始 elseif (p.next == p) // PREV_TERMINATOR continue restartFromHead; else { // p is first node // 将当前节点设置为第一个. NEXT.set(newNode, p); // CAS piggyback // cas 更新相关属性, 原有头结点的前置属性,以及新的头结点等. if (PREV.compareAndSet(p, 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 != h) // hop two nodes at a time; failure is OK HEAD.weakCompareAndSet(this, h, newNode); return; } // Lost CAS race to another thread; re-read prev } } }
privatevoidlinkLast(E e) { final Node<E> newNode = newNode(Objects.requireNonNull(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; elseif (p.prev == p) // NEXT_TERMINATOR continue restartFromTail; else { // p is last node PREV.set(newNode, p); // CAS piggyback if (NEXT.compareAndSet(p, 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; failure is OK TAIL.weakCompareAndSet(this, t, newNode); return; } // Lost CAS race to another thread; re-read next } } }
public E pollFirst() { restart: for (;;) { for (Node<E> first = first(), p = first;;) { // 队头节点, cas更改属性 final E item; if ((item = p.item) != null) { // recheck for linearizability if (first.prev != null) continue restart; if (ITEM.compareAndSet(p, item, null)) { unlink(p); return item; } } // 已出队,重新开始 if (p == (p = p.next)) continue restart; // p为空,队列为空,返回空 if (p == null) { if (first.prev != null) continue restart; returnnull; } } } }
public E pollLast() { restart: for (;;) { for (Node<E> last = last(), p = last;;) { final E item; if ((item = p.item) != null) { // recheck for linearizability if (last.next != null) continue restart; if (ITEM.compareAndSet(p, item, null)) { unlink(p); return item; } } if (p == (p = p.prev)) continue restart; if (p == null) { if (last.next != null) continue restart; returnnull; } } } }