jaroslav@1890: /*
jaroslav@1890: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1890: *
jaroslav@1890: * This code is free software; you can redistribute it and/or modify it
jaroslav@1890: * under the terms of the GNU General Public License version 2 only, as
jaroslav@1890: * published by the Free Software Foundation. Oracle designates this
jaroslav@1890: * particular file as subject to the "Classpath" exception as provided
jaroslav@1890: * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1890: *
jaroslav@1890: * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1890: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1890: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
jaroslav@1890: * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1890: * accompanied this code).
jaroslav@1890: *
jaroslav@1890: * You should have received a copy of the GNU General Public License version
jaroslav@1890: * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1890: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1890: *
jaroslav@1890: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1890: * or visit www.oracle.com if you need additional information or have any
jaroslav@1890: * questions.
jaroslav@1890: */
jaroslav@1890:
jaroslav@1890: /*
jaroslav@1890: * This file is available under and governed by the GNU General Public
jaroslav@1890: * License version 2 only, as published by the Free Software Foundation.
jaroslav@1890: * However, the following notice accompanied the original version of this
jaroslav@1890: * file:
jaroslav@1890: *
jaroslav@1890: * Written by Doug Lea and Martin Buchholz with assistance from members of
jaroslav@1890: * JCP JSR-166 Expert Group and released to the public domain, as explained
jaroslav@1890: * at http://creativecommons.org/publicdomain/zero/1.0/
jaroslav@1890: */
jaroslav@1890:
jaroslav@1890: package java.util.concurrent;
jaroslav@1890:
jaroslav@1890: import java.util.AbstractQueue;
jaroslav@1890: import java.util.ArrayList;
jaroslav@1890: import java.util.Collection;
jaroslav@1890: import java.util.Iterator;
jaroslav@1890: import java.util.NoSuchElementException;
jaroslav@1890: import java.util.Queue;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * An unbounded thread-safe {@linkplain Queue queue} based on linked nodes.
jaroslav@1890: * This queue orders elements FIFO (first-in-first-out).
jaroslav@1890: * The head of the queue is that element that has been on the
jaroslav@1890: * queue the longest time.
jaroslav@1890: * The tail of the queue is that element that has been on the
jaroslav@1890: * queue the shortest time. New elements
jaroslav@1890: * are inserted at the tail of the queue, and the queue retrieval
jaroslav@1890: * operations obtain elements at the head of the queue.
jaroslav@1890: * A {@code ConcurrentLinkedQueue} is an appropriate choice when
jaroslav@1890: * many threads will share access to a common collection.
jaroslav@1890: * Like most other concurrent collection implementations, this class
jaroslav@1890: * does not permit the use of {@code null} elements.
jaroslav@1890: *
jaroslav@1890: *
This implementation employs an efficient "wait-free"
jaroslav@1890: * algorithm based on one described in Simple,
jaroslav@1890: * Fast, and Practical Non-Blocking and Blocking Concurrent Queue
jaroslav@1890: * Algorithms by Maged M. Michael and Michael L. Scott.
jaroslav@1890: *
jaroslav@1890: *
Iterators are weakly consistent, returning elements
jaroslav@1890: * reflecting the state of the queue at some point at or since the
jaroslav@1890: * creation of the iterator. They do not throw {@link
jaroslav@1890: * java.util.ConcurrentModificationException}, and may proceed concurrently
jaroslav@1890: * with other operations. Elements contained in the queue since the creation
jaroslav@1890: * of the iterator will be returned exactly once.
jaroslav@1890: *
jaroslav@1890: *
Beware that, unlike in most collections, the {@code size} method
jaroslav@1890: * is NOT a constant-time operation. Because of the
jaroslav@1890: * asynchronous nature of these queues, determining the current number
jaroslav@1890: * of elements requires a traversal of the elements, and so may report
jaroslav@1890: * inaccurate results if this collection is modified during traversal.
jaroslav@1890: * Additionally, the bulk operations {@code addAll},
jaroslav@1890: * {@code removeAll}, {@code retainAll}, {@code containsAll},
jaroslav@1890: * {@code equals}, and {@code toArray} are not guaranteed
jaroslav@1890: * to be performed atomically. For example, an iterator operating
jaroslav@1890: * concurrently with an {@code addAll} operation might view only some
jaroslav@1890: * of the added elements.
jaroslav@1890: *
jaroslav@1890: *
This class and its iterator implement all of the optional
jaroslav@1890: * methods of the {@link Queue} and {@link Iterator} interfaces.
jaroslav@1890: *
jaroslav@1890: *
Memory consistency effects: As with other concurrent
jaroslav@1890: * collections, actions in a thread prior to placing an object into a
jaroslav@1890: * {@code ConcurrentLinkedQueue}
jaroslav@1890: * happen-before
jaroslav@1890: * actions subsequent to the access or removal of that element from
jaroslav@1890: * the {@code ConcurrentLinkedQueue} in another thread.
jaroslav@1890: *
jaroslav@1890: *
This class is a member of the
jaroslav@1890: *
jaroslav@1890: * Java Collections Framework.
jaroslav@1890: *
jaroslav@1890: * @since 1.5
jaroslav@1890: * @author Doug Lea
jaroslav@1890: * @param the type of elements held in this collection
jaroslav@1890: *
jaroslav@1890: */
jaroslav@1890: public class ConcurrentLinkedQueue extends AbstractQueue
jaroslav@1890: implements Queue, java.io.Serializable {
jaroslav@1890: private static final long serialVersionUID = 196745693267521676L;
jaroslav@1890:
jaroslav@1890: /*
jaroslav@1890: * This is a modification of the Michael & Scott algorithm,
jaroslav@1890: * adapted for a garbage-collected environment, with support for
jaroslav@1890: * interior node deletion (to support remove(Object)). For
jaroslav@1890: * explanation, read the paper.
jaroslav@1890: *
jaroslav@1890: * Note that like most non-blocking algorithms in this package,
jaroslav@1890: * this implementation relies on the fact that in garbage
jaroslav@1890: * collected systems, there is no possibility of ABA problems due
jaroslav@1890: * to recycled nodes, so there is no need to use "counted
jaroslav@1890: * pointers" or related techniques seen in versions used in
jaroslav@1890: * non-GC'ed settings.
jaroslav@1890: *
jaroslav@1890: * The fundamental invariants are:
jaroslav@1890: * - There is exactly one (last) Node with a null next reference,
jaroslav@1890: * which is CASed when enqueueing. This last Node can be
jaroslav@1890: * reached in O(1) time from tail, but tail is merely an
jaroslav@1890: * optimization - it can always be reached in O(N) time from
jaroslav@1890: * head as well.
jaroslav@1890: * - The elements contained in the queue are the non-null items in
jaroslav@1890: * Nodes that are reachable from head. CASing the item
jaroslav@1890: * reference of a Node to null atomically removes it from the
jaroslav@1890: * queue. Reachability of all elements from head must remain
jaroslav@1890: * true even in the case of concurrent modifications that cause
jaroslav@1890: * head to advance. A dequeued Node may remain in use
jaroslav@1890: * indefinitely due to creation of an Iterator or simply a
jaroslav@1890: * poll() that has lost its time slice.
jaroslav@1890: *
jaroslav@1890: * The above might appear to imply that all Nodes are GC-reachable
jaroslav@1890: * from a predecessor dequeued Node. That would cause two problems:
jaroslav@1890: * - allow a rogue Iterator to cause unbounded memory retention
jaroslav@1890: * - cause cross-generational linking of old Nodes to new Nodes if
jaroslav@1890: * a Node was tenured while live, which generational GCs have a
jaroslav@1890: * hard time dealing with, causing repeated major collections.
jaroslav@1890: * However, only non-deleted Nodes need to be reachable from
jaroslav@1890: * dequeued Nodes, and reachability does not necessarily have to
jaroslav@1890: * be of the kind understood by the GC. We use the trick of
jaroslav@1890: * linking a Node that has just been dequeued to itself. Such a
jaroslav@1890: * self-link implicitly means to advance to head.
jaroslav@1890: *
jaroslav@1890: * Both head and tail are permitted to lag. In fact, failing to
jaroslav@1890: * update them every time one could is a significant optimization
jaroslav@1890: * (fewer CASes). As with LinkedTransferQueue (see the internal
jaroslav@1890: * documentation for that class), we use a slack threshold of two;
jaroslav@1890: * that is, we update head/tail when the current pointer appears
jaroslav@1890: * to be two or more steps away from the first/last node.
jaroslav@1890: *
jaroslav@1890: * Since head and tail are updated concurrently and independently,
jaroslav@1890: * it is possible for tail to lag behind head (why not)?
jaroslav@1890: *
jaroslav@1890: * CASing a Node's item reference to null atomically removes the
jaroslav@1890: * element from the queue. Iterators skip over Nodes with null
jaroslav@1890: * items. Prior implementations of this class had a race between
jaroslav@1890: * poll() and remove(Object) where the same element would appear
jaroslav@1890: * to be successfully removed by two concurrent operations. The
jaroslav@1890: * method remove(Object) also lazily unlinks deleted Nodes, but
jaroslav@1890: * this is merely an optimization.
jaroslav@1890: *
jaroslav@1890: * When constructing a Node (before enqueuing it) we avoid paying
jaroslav@1890: * for a volatile write to item by using Unsafe.putObject instead
jaroslav@1890: * of a normal write. This allows the cost of enqueue to be
jaroslav@1890: * "one-and-a-half" CASes.
jaroslav@1890: *
jaroslav@1890: * Both head and tail may or may not point to a Node with a
jaroslav@1890: * non-null item. If the queue is empty, all items must of course
jaroslav@1890: * be null. Upon creation, both head and tail refer to a dummy
jaroslav@1890: * Node with null item. Both head and tail are only updated using
jaroslav@1890: * CAS, so they never regress, although again this is merely an
jaroslav@1890: * optimization.
jaroslav@1890: */
jaroslav@1890:
jaroslav@1890: private static class Node {
jaroslav@1890: volatile E item;
jaroslav@1890: volatile Node next;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Constructs a new node. Uses relaxed write because item can
jaroslav@1890: * only be seen after publication via casNext.
jaroslav@1890: */
jaroslav@1890: Node(E item) {
jaroslav@1890: UNSAFE.putObject(this, itemOffset, item);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: boolean casItem(E cmp, E val) {
jaroslav@1890: return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: void lazySetNext(Node val) {
jaroslav@1890: UNSAFE.putOrderedObject(this, nextOffset, val);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: boolean casNext(Node cmp, Node val) {
jaroslav@1890: return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: // Unsafe mechanics
jaroslav@1890:
jaroslav@1890: private static final sun.misc.Unsafe UNSAFE;
jaroslav@1890: private static final long itemOffset;
jaroslav@1890: private static final long nextOffset;
jaroslav@1890:
jaroslav@1890: static {
jaroslav@1890: try {
jaroslav@1890: UNSAFE = sun.misc.Unsafe.getUnsafe();
jaroslav@1890: Class k = Node.class;
jaroslav@1890: itemOffset = UNSAFE.objectFieldOffset
jaroslav@1890: (k.getDeclaredField("item"));
jaroslav@1890: nextOffset = UNSAFE.objectFieldOffset
jaroslav@1890: (k.getDeclaredField("next"));
jaroslav@1890: } catch (Exception e) {
jaroslav@1890: throw new Error(e);
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * A node from which the first live (non-deleted) node (if any)
jaroslav@1890: * can be reached in O(1) time.
jaroslav@1890: * Invariants:
jaroslav@1890: * - all live nodes are reachable from head via succ()
jaroslav@1890: * - head != null
jaroslav@1890: * - (tmp = head).next != tmp || tmp != head
jaroslav@1890: * Non-invariants:
jaroslav@1890: * - head.item may or may not be null.
jaroslav@1890: * - it is permitted for tail to lag behind head, that is, for tail
jaroslav@1890: * to not be reachable from head!
jaroslav@1890: */
jaroslav@1890: private transient volatile Node head;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * A node from which the last node on list (that is, the unique
jaroslav@1890: * node with node.next == null) can be reached in O(1) time.
jaroslav@1890: * Invariants:
jaroslav@1890: * - the last node is always reachable from tail via succ()
jaroslav@1890: * - tail != null
jaroslav@1890: * Non-invariants:
jaroslav@1890: * - tail.item may or may not be null.
jaroslav@1890: * - it is permitted for tail to lag behind head, that is, for tail
jaroslav@1890: * to not be reachable from head!
jaroslav@1890: * - tail.next may or may not be self-pointing to tail.
jaroslav@1890: */
jaroslav@1890: private transient volatile Node tail;
jaroslav@1890:
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Creates a {@code ConcurrentLinkedQueue} that is initially empty.
jaroslav@1890: */
jaroslav@1890: public ConcurrentLinkedQueue() {
jaroslav@1890: head = tail = new Node(null);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Creates a {@code ConcurrentLinkedQueue}
jaroslav@1890: * initially containing the elements of the given collection,
jaroslav@1890: * added in traversal order of the collection's iterator.
jaroslav@1890: *
jaroslav@1890: * @param c the collection of elements to initially contain
jaroslav@1890: * @throws NullPointerException if the specified collection or any
jaroslav@1890: * of its elements are null
jaroslav@1890: */
jaroslav@1890: public ConcurrentLinkedQueue(Collection extends E> c) {
jaroslav@1890: Node h = null, t = null;
jaroslav@1890: for (E e : c) {
jaroslav@1890: checkNotNull(e);
jaroslav@1890: Node newNode = new Node(e);
jaroslav@1890: if (h == null)
jaroslav@1890: h = t = newNode;
jaroslav@1890: else {
jaroslav@1890: t.lazySetNext(newNode);
jaroslav@1890: t = newNode;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: if (h == null)
jaroslav@1890: h = t = new Node(null);
jaroslav@1890: head = h;
jaroslav@1890: tail = t;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: // Have to override just to update the javadoc
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Inserts the specified element at the tail of this queue.
jaroslav@1890: * As the queue is unbounded, this method will never throw
jaroslav@1890: * {@link IllegalStateException} or return {@code false}.
jaroslav@1890: *
jaroslav@1890: * @return {@code true} (as specified by {@link Collection#add})
jaroslav@1890: * @throws NullPointerException if the specified element is null
jaroslav@1890: */
jaroslav@1890: public boolean add(E e) {
jaroslav@1890: return offer(e);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Try to CAS head to p. If successful, repoint old head to itself
jaroslav@1890: * as sentinel for succ(), below.
jaroslav@1890: */
jaroslav@1890: final void updateHead(Node h, Node p) {
jaroslav@1890: if (h != p && casHead(h, p))
jaroslav@1890: h.lazySetNext(h);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns the successor of p, or the head node if p.next has been
jaroslav@1890: * linked to self, which will only be true if traversing with a
jaroslav@1890: * stale pointer that is now off the list.
jaroslav@1890: */
jaroslav@1890: final Node succ(Node p) {
jaroslav@1890: Node next = p.next;
jaroslav@1890: return (p == next) ? head : next;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Inserts the specified element at the tail of this queue.
jaroslav@1890: * As the queue is unbounded, this method will never return {@code false}.
jaroslav@1890: *
jaroslav@1890: * @return {@code true} (as specified by {@link Queue#offer})
jaroslav@1890: * @throws NullPointerException if the specified element is null
jaroslav@1890: */
jaroslav@1890: public boolean offer(E e) {
jaroslav@1890: checkNotNull(e);
jaroslav@1890: final Node newNode = new Node(e);
jaroslav@1890:
jaroslav@1890: for (Node t = tail, p = t;;) {
jaroslav@1890: Node q = p.next;
jaroslav@1890: if (q == null) {
jaroslav@1890: // p is last node
jaroslav@1890: if (p.casNext(null, newNode)) {
jaroslav@1890: // Successful CAS is the linearization point
jaroslav@1890: // for e to become an element of this queue,
jaroslav@1890: // and for newNode to become "live".
jaroslav@1890: if (p != t) // hop two nodes at a time
jaroslav@1890: casTail(t, newNode); // Failure is OK.
jaroslav@1890: return true;
jaroslav@1890: }
jaroslav@1890: // Lost CAS race to another thread; re-read next
jaroslav@1890: }
jaroslav@1890: else if (p == q)
jaroslav@1890: // We have fallen off list. If tail is unchanged, it
jaroslav@1890: // will also be off-list, in which case we need to
jaroslav@1890: // jump to head, from which all live nodes are always
jaroslav@1890: // reachable. Else the new tail is a better bet.
jaroslav@1890: p = (t != (t = tail)) ? t : head;
jaroslav@1890: else
jaroslav@1890: // Check for tail updates after two hops.
jaroslav@1890: p = (p != t && t != (t = tail)) ? t : q;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: public E poll() {
jaroslav@1890: restartFromHead:
jaroslav@1890: for (;;) {
jaroslav@1890: for (Node h = head, p = h, q;;) {
jaroslav@1890: E item = p.item;
jaroslav@1890:
jaroslav@1890: if (item != null && p.casItem(item, null)) {
jaroslav@1890: // Successful CAS is the linearization point
jaroslav@1890: // for item to be removed from this queue.
jaroslav@1890: if (p != h) // hop two nodes at a time
jaroslav@1890: updateHead(h, ((q = p.next) != null) ? q : p);
jaroslav@1890: return item;
jaroslav@1890: }
jaroslav@1890: else if ((q = p.next) == null) {
jaroslav@1890: updateHead(h, p);
jaroslav@1890: return null;
jaroslav@1890: }
jaroslav@1890: else if (p == q)
jaroslav@1890: continue restartFromHead;
jaroslav@1890: else
jaroslav@1890: p = q;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: public E peek() {
jaroslav@1890: restartFromHead:
jaroslav@1890: for (;;) {
jaroslav@1890: for (Node h = head, p = h, q;;) {
jaroslav@1890: E item = p.item;
jaroslav@1890: if (item != null || (q = p.next) == null) {
jaroslav@1890: updateHead(h, p);
jaroslav@1890: return item;
jaroslav@1890: }
jaroslav@1890: else if (p == q)
jaroslav@1890: continue restartFromHead;
jaroslav@1890: else
jaroslav@1890: p = q;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns the first live (non-deleted) node on list, or null if none.
jaroslav@1890: * This is yet another variant of poll/peek; here returning the
jaroslav@1890: * first node, not element. We could make peek() a wrapper around
jaroslav@1890: * first(), but that would cost an extra volatile read of item,
jaroslav@1890: * and the need to add a retry loop to deal with the possibility
jaroslav@1890: * of losing a race to a concurrent poll().
jaroslav@1890: */
jaroslav@1890: Node first() {
jaroslav@1890: restartFromHead:
jaroslav@1890: for (;;) {
jaroslav@1890: for (Node h = head, p = h, q;;) {
jaroslav@1890: boolean hasItem = (p.item != null);
jaroslav@1890: if (hasItem || (q = p.next) == null) {
jaroslav@1890: updateHead(h, p);
jaroslav@1890: return hasItem ? p : null;
jaroslav@1890: }
jaroslav@1890: else if (p == q)
jaroslav@1890: continue restartFromHead;
jaroslav@1890: else
jaroslav@1890: p = q;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns {@code true} if this queue contains no elements.
jaroslav@1890: *
jaroslav@1890: * @return {@code true} if this queue contains no elements
jaroslav@1890: */
jaroslav@1890: public boolean isEmpty() {
jaroslav@1890: return first() == null;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns the number of elements in this queue. If this queue
jaroslav@1890: * contains more than {@code Integer.MAX_VALUE} elements, returns
jaroslav@1890: * {@code Integer.MAX_VALUE}.
jaroslav@1890: *
jaroslav@1890: * Beware that, unlike in most collections, this method is
jaroslav@1890: * NOT a constant-time operation. Because of the
jaroslav@1890: * asynchronous nature of these queues, determining the current
jaroslav@1890: * number of elements requires an O(n) traversal.
jaroslav@1890: * Additionally, if elements are added or removed during execution
jaroslav@1890: * of this method, the returned result may be inaccurate. Thus,
jaroslav@1890: * this method is typically not very useful in concurrent
jaroslav@1890: * applications.
jaroslav@1890: *
jaroslav@1890: * @return the number of elements in this queue
jaroslav@1890: */
jaroslav@1890: public int size() {
jaroslav@1890: int count = 0;
jaroslav@1890: for (Node p = first(); p != null; p = succ(p))
jaroslav@1890: if (p.item != null)
jaroslav@1890: // Collection.size() spec says to max out
jaroslav@1890: if (++count == Integer.MAX_VALUE)
jaroslav@1890: break;
jaroslav@1890: return count;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns {@code true} if this queue contains the specified element.
jaroslav@1890: * More formally, returns {@code true} if and only if this queue contains
jaroslav@1890: * at least one element {@code e} such that {@code o.equals(e)}.
jaroslav@1890: *
jaroslav@1890: * @param o object to be checked for containment in this queue
jaroslav@1890: * @return {@code true} if this queue contains the specified element
jaroslav@1890: */
jaroslav@1890: public boolean contains(Object o) {
jaroslav@1890: if (o == null) return false;
jaroslav@1890: for (Node p = first(); p != null; p = succ(p)) {
jaroslav@1890: E item = p.item;
jaroslav@1890: if (item != null && o.equals(item))
jaroslav@1890: return true;
jaroslav@1890: }
jaroslav@1890: return false;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Removes a single instance of the specified element from this queue,
jaroslav@1890: * if it is present. More formally, removes an element {@code e} such
jaroslav@1890: * that {@code o.equals(e)}, if this queue contains one or more such
jaroslav@1890: * elements.
jaroslav@1890: * Returns {@code true} if this queue contained the specified element
jaroslav@1890: * (or equivalently, if this queue changed as a result of the call).
jaroslav@1890: *
jaroslav@1890: * @param o element to be removed from this queue, if present
jaroslav@1890: * @return {@code true} if this queue changed as a result of the call
jaroslav@1890: */
jaroslav@1890: public boolean remove(Object o) {
jaroslav@1890: if (o == null) return false;
jaroslav@1890: Node pred = null;
jaroslav@1890: for (Node p = first(); p != null; p = succ(p)) {
jaroslav@1890: E item = p.item;
jaroslav@1890: if (item != null &&
jaroslav@1890: o.equals(item) &&
jaroslav@1890: p.casItem(item, null)) {
jaroslav@1890: Node next = succ(p);
jaroslav@1890: if (pred != null && next != null)
jaroslav@1890: pred.casNext(p, next);
jaroslav@1890: return true;
jaroslav@1890: }
jaroslav@1890: pred = p;
jaroslav@1890: }
jaroslav@1890: return false;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Appends all of the elements in the specified collection to the end of
jaroslav@1890: * this queue, in the order that they are returned by the specified
jaroslav@1890: * collection's iterator. Attempts to {@code addAll} of a queue to
jaroslav@1890: * itself result in {@code IllegalArgumentException}.
jaroslav@1890: *
jaroslav@1890: * @param c the elements to be inserted into this queue
jaroslav@1890: * @return {@code true} if this queue changed as a result of the call
jaroslav@1890: * @throws NullPointerException if the specified collection or any
jaroslav@1890: * of its elements are null
jaroslav@1890: * @throws IllegalArgumentException if the collection is this queue
jaroslav@1890: */
jaroslav@1890: public boolean addAll(Collection extends E> c) {
jaroslav@1890: if (c == this)
jaroslav@1890: // As historically specified in AbstractQueue#addAll
jaroslav@1890: throw new IllegalArgumentException();
jaroslav@1890:
jaroslav@1890: // Copy c into a private chain of Nodes
jaroslav@1890: Node beginningOfTheEnd = null, last = null;
jaroslav@1890: for (E e : c) {
jaroslav@1890: checkNotNull(e);
jaroslav@1890: Node newNode = new Node(e);
jaroslav@1890: if (beginningOfTheEnd == null)
jaroslav@1890: beginningOfTheEnd = last = newNode;
jaroslav@1890: else {
jaroslav@1890: last.lazySetNext(newNode);
jaroslav@1890: last = newNode;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: if (beginningOfTheEnd == null)
jaroslav@1890: return false;
jaroslav@1890:
jaroslav@1890: // Atomically append the chain at the tail of this collection
jaroslav@1890: for (Node t = tail, p = t;;) {
jaroslav@1890: Node q = p.next;
jaroslav@1890: if (q == null) {
jaroslav@1890: // p is last node
jaroslav@1890: if (p.casNext(null, beginningOfTheEnd)) {
jaroslav@1890: // Successful CAS is the linearization point
jaroslav@1890: // for all elements to be added to this queue.
jaroslav@1890: if (!casTail(t, last)) {
jaroslav@1890: // Try a little harder to update tail,
jaroslav@1890: // since we may be adding many elements.
jaroslav@1890: t = tail;
jaroslav@1890: if (last.next == null)
jaroslav@1890: casTail(t, last);
jaroslav@1890: }
jaroslav@1890: return true;
jaroslav@1890: }
jaroslav@1890: // Lost CAS race to another thread; re-read next
jaroslav@1890: }
jaroslav@1890: else if (p == q)
jaroslav@1890: // We have fallen off list. If tail is unchanged, it
jaroslav@1890: // will also be off-list, in which case we need to
jaroslav@1890: // jump to head, from which all live nodes are always
jaroslav@1890: // reachable. Else the new tail is a better bet.
jaroslav@1890: p = (t != (t = tail)) ? t : head;
jaroslav@1890: else
jaroslav@1890: // Check for tail updates after two hops.
jaroslav@1890: p = (p != t && t != (t = tail)) ? t : q;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns an array containing all of the elements in this queue, in
jaroslav@1890: * proper sequence.
jaroslav@1890: *
jaroslav@1890: * The returned array will be "safe" in that no references to it are
jaroslav@1890: * maintained by this queue. (In other words, this method must allocate
jaroslav@1890: * a new array). The caller is thus free to modify the returned array.
jaroslav@1890: *
jaroslav@1890: *
This method acts as bridge between array-based and collection-based
jaroslav@1890: * APIs.
jaroslav@1890: *
jaroslav@1890: * @return an array containing all of the elements in this queue
jaroslav@1890: */
jaroslav@1890: public Object[] toArray() {
jaroslav@1890: // Use ArrayList to deal with resizing.
jaroslav@1890: ArrayList al = new ArrayList();
jaroslav@1890: for (Node p = first(); p != null; p = succ(p)) {
jaroslav@1890: E item = p.item;
jaroslav@1890: if (item != null)
jaroslav@1890: al.add(item);
jaroslav@1890: }
jaroslav@1890: return al.toArray();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns an array containing all of the elements in this queue, in
jaroslav@1890: * proper sequence; the runtime type of the returned array is that of
jaroslav@1890: * the specified array. If the queue fits in the specified array, it
jaroslav@1890: * is returned therein. Otherwise, a new array is allocated with the
jaroslav@1890: * runtime type of the specified array and the size of this queue.
jaroslav@1890: *
jaroslav@1890: * If this queue fits in the specified array with room to spare
jaroslav@1890: * (i.e., the array has more elements than this queue), the element in
jaroslav@1890: * the array immediately following the end of the queue is set to
jaroslav@1890: * {@code null}.
jaroslav@1890: *
jaroslav@1890: *
Like the {@link #toArray()} method, this method acts as bridge between
jaroslav@1890: * array-based and collection-based APIs. Further, this method allows
jaroslav@1890: * precise control over the runtime type of the output array, and may,
jaroslav@1890: * under certain circumstances, be used to save allocation costs.
jaroslav@1890: *
jaroslav@1890: *
Suppose {@code x} is a queue known to contain only strings.
jaroslav@1890: * The following code can be used to dump the queue into a newly
jaroslav@1890: * allocated array of {@code String}:
jaroslav@1890: *
jaroslav@1890: *
jaroslav@1890: * String[] y = x.toArray(new String[0]);
jaroslav@1890: *
jaroslav@1890: * Note that {@code toArray(new Object[0])} is identical in function to
jaroslav@1890: * {@code toArray()}.
jaroslav@1890: *
jaroslav@1890: * @param a the array into which the elements of the queue are to
jaroslav@1890: * be stored, if it is big enough; otherwise, a new array of the
jaroslav@1890: * same runtime type is allocated for this purpose
jaroslav@1890: * @return an array containing all of the elements in this queue
jaroslav@1890: * @throws ArrayStoreException if the runtime type of the specified array
jaroslav@1890: * is not a supertype of the runtime type of every element in
jaroslav@1890: * this queue
jaroslav@1890: * @throws NullPointerException if the specified array is null
jaroslav@1890: */
jaroslav@1890: @SuppressWarnings("unchecked")
jaroslav@1890: public T[] toArray(T[] a) {
jaroslav@1890: // try to use sent-in array
jaroslav@1890: int k = 0;
jaroslav@1890: Node p;
jaroslav@1890: for (p = first(); p != null && k < a.length; p = succ(p)) {
jaroslav@1890: E item = p.item;
jaroslav@1890: if (item != null)
jaroslav@1890: a[k++] = (T)item;
jaroslav@1890: }
jaroslav@1890: if (p == null) {
jaroslav@1890: if (k < a.length)
jaroslav@1890: a[k] = null;
jaroslav@1890: return a;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: // If won't fit, use ArrayList version
jaroslav@1890: ArrayList al = new ArrayList();
jaroslav@1890: for (Node q = first(); q != null; q = succ(q)) {
jaroslav@1890: E item = q.item;
jaroslav@1890: if (item != null)
jaroslav@1890: al.add(item);
jaroslav@1890: }
jaroslav@1890: return al.toArray(a);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns an iterator over the elements in this queue in proper sequence.
jaroslav@1890: * The elements will be returned in order from first (head) to last (tail).
jaroslav@1890: *
jaroslav@1890: * The returned iterator is a "weakly consistent" iterator that
jaroslav@1890: * will never throw {@link java.util.ConcurrentModificationException
jaroslav@1890: * ConcurrentModificationException}, and guarantees to traverse
jaroslav@1890: * elements as they existed upon construction of the iterator, and
jaroslav@1890: * may (but is not guaranteed to) reflect any modifications
jaroslav@1890: * subsequent to construction.
jaroslav@1890: *
jaroslav@1890: * @return an iterator over the elements in this queue in proper sequence
jaroslav@1890: */
jaroslav@1890: public Iterator iterator() {
jaroslav@1890: return new Itr();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: private class Itr implements Iterator {
jaroslav@1890: /**
jaroslav@1890: * Next node to return item for.
jaroslav@1890: */
jaroslav@1890: private Node nextNode;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * nextItem holds on to item fields because once we claim
jaroslav@1890: * that an element exists in hasNext(), we must return it in
jaroslav@1890: * the following next() call even if it was in the process of
jaroslav@1890: * being removed when hasNext() was called.
jaroslav@1890: */
jaroslav@1890: private E nextItem;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Node of the last returned item, to support remove.
jaroslav@1890: */
jaroslav@1890: private Node lastRet;
jaroslav@1890:
jaroslav@1890: Itr() {
jaroslav@1890: advance();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Moves to next valid node and returns item to return for
jaroslav@1890: * next(), or null if no such.
jaroslav@1890: */
jaroslav@1890: private E advance() {
jaroslav@1890: lastRet = nextNode;
jaroslav@1890: E x = nextItem;
jaroslav@1890:
jaroslav@1890: Node pred, p;
jaroslav@1890: if (nextNode == null) {
jaroslav@1890: p = first();
jaroslav@1890: pred = null;
jaroslav@1890: } else {
jaroslav@1890: pred = nextNode;
jaroslav@1890: p = succ(nextNode);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: for (;;) {
jaroslav@1890: if (p == null) {
jaroslav@1890: nextNode = null;
jaroslav@1890: nextItem = null;
jaroslav@1890: return x;
jaroslav@1890: }
jaroslav@1890: E item = p.item;
jaroslav@1890: if (item != null) {
jaroslav@1890: nextNode = p;
jaroslav@1890: nextItem = item;
jaroslav@1890: return x;
jaroslav@1890: } else {
jaroslav@1890: // skip over nulls
jaroslav@1890: Node next = succ(p);
jaroslav@1890: if (pred != null && next != null)
jaroslav@1890: pred.casNext(p, next);
jaroslav@1890: p = next;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: public boolean hasNext() {
jaroslav@1890: return nextNode != null;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: public E next() {
jaroslav@1890: if (nextNode == null) throw new NoSuchElementException();
jaroslav@1890: return advance();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: public void remove() {
jaroslav@1890: Node l = lastRet;
jaroslav@1890: if (l == null) throw new IllegalStateException();
jaroslav@1890: // rely on a future traversal to relink.
jaroslav@1890: l.item = null;
jaroslav@1890: lastRet = null;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Saves the state to a stream (that is, serializes it).
jaroslav@1890: *
jaroslav@1890: * @serialData All of the elements (each an {@code E}) in
jaroslav@1890: * the proper order, followed by a null
jaroslav@1890: * @param s the stream
jaroslav@1890: */
jaroslav@1890: private void writeObject(java.io.ObjectOutputStream s)
jaroslav@1890: throws java.io.IOException {
jaroslav@1890:
jaroslav@1890: // Write out any hidden stuff
jaroslav@1890: s.defaultWriteObject();
jaroslav@1890:
jaroslav@1890: // Write out all elements in the proper order.
jaroslav@1890: for (Node p = first(); p != null; p = succ(p)) {
jaroslav@1890: Object item = p.item;
jaroslav@1890: if (item != null)
jaroslav@1890: s.writeObject(item);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: // Use trailing null as sentinel
jaroslav@1890: s.writeObject(null);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Reconstitutes the instance from a stream (that is, deserializes it).
jaroslav@1890: * @param s the stream
jaroslav@1890: */
jaroslav@1890: private void readObject(java.io.ObjectInputStream s)
jaroslav@1890: throws java.io.IOException, ClassNotFoundException {
jaroslav@1890: s.defaultReadObject();
jaroslav@1890:
jaroslav@1890: // Read in elements until trailing null sentinel found
jaroslav@1890: Node h = null, t = null;
jaroslav@1890: Object item;
jaroslav@1890: while ((item = s.readObject()) != null) {
jaroslav@1890: @SuppressWarnings("unchecked")
jaroslav@1890: Node newNode = new Node((E) item);
jaroslav@1890: if (h == null)
jaroslav@1890: h = t = newNode;
jaroslav@1890: else {
jaroslav@1890: t.lazySetNext(newNode);
jaroslav@1890: t = newNode;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: if (h == null)
jaroslav@1890: h = t = new Node(null);
jaroslav@1890: head = h;
jaroslav@1890: tail = t;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Throws NullPointerException if argument is null.
jaroslav@1890: *
jaroslav@1890: * @param v the element
jaroslav@1890: */
jaroslav@1890: private static void checkNotNull(Object v) {
jaroslav@1890: if (v == null)
jaroslav@1890: throw new NullPointerException();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: private boolean casTail(Node cmp, Node val) {
jaroslav@1890: return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: private boolean casHead(Node cmp, Node val) {
jaroslav@1890: return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: // Unsafe mechanics
jaroslav@1890:
jaroslav@1890: private static final sun.misc.Unsafe UNSAFE;
jaroslav@1890: private static final long headOffset;
jaroslav@1890: private static final long tailOffset;
jaroslav@1890: static {
jaroslav@1890: try {
jaroslav@1890: UNSAFE = sun.misc.Unsafe.getUnsafe();
jaroslav@1890: Class k = ConcurrentLinkedQueue.class;
jaroslav@1890: headOffset = UNSAFE.objectFieldOffset
jaroslav@1890: (k.getDeclaredField("head"));
jaroslav@1890: tailOffset = UNSAFE.objectFieldOffset
jaroslav@1890: (k.getDeclaredField("tail"));
jaroslav@1890: } catch (Exception e) {
jaroslav@1890: throw new Error(e);
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: }