/** * Returns the first node, the unique node p for which: * p.prev == null && p.next != p * The returned node may or may not be logically deleted. * Guarantees that head is set to the returned node. */ Node<E> first() { restartFromHead: for (;;) for (Node<E> h = head, p = h, q;;) { 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; else if (p == h // It is possible that p is PREV_TERMINATOR, // but if so, the CAS is guaranteed to fail. || casHead(h, p)) return p; else continue restartFromHead; } }
/** * Guarantees that any node which was unlinked before a call to * this method will be unreachable from head after it returns. * Does not guarantee to eliminate slack, only that head will * point to a node that was active while this method was running. */ private final void updateHead() { // Either head already points to an active node, or we keep // trying to cas it to the first node until it does. Node<E> h, p, q; restartFromHead: while ((h = head).item == null && (p = h.prev) != null) { for (;;) { if ((q = p.prev) == null || (q = (p = q).prev) == null) { // It is possible that p is PREV_TERMINATOR, // but if so, the CAS is guaranteed to fail. if (casHead(h, p)) return; else continue restartFromHead; } else if (h != head) continue restartFromHead; else p = q; } } }
casHead(h, newNode); // Failure is OK. return;