ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ConcurrentLinkedQueue.java
Revision: 1.48
Committed: Tue Jul 7 23:17:20 2009 UTC (14 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.47: +346 -137 lines
Log Message:
6785442: ConcurrentLinkedQueue.remove() and poll() can both remove the same element

File Contents

# Content
1 /*
2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/licenses/publicdomain
5 */
6
7 package java.util.concurrent;
8 import java.util.*;
9 import java.util.concurrent.atomic.*;
10
11
12 /**
13 * An unbounded thread-safe {@linkplain Queue queue} based on linked nodes.
14 * This queue orders elements FIFO (first-in-first-out).
15 * The <em>head</em> of the queue is that element that has been on the
16 * queue the longest time.
17 * The <em>tail</em> of the queue is that element that has been on the
18 * queue the shortest time. New elements
19 * are inserted at the tail of the queue, and the queue retrieval
20 * operations obtain elements at the head of the queue.
21 * A {@code ConcurrentLinkedQueue} is an appropriate choice when
22 * many threads will share access to a common collection.
23 * This queue does not permit {@code null} elements.
24 *
25 * <p>This implementation employs an efficient &quot;wait-free&quot;
26 * algorithm based on one described in <a
27 * href="http://www.cs.rochester.edu/u/michael/PODC96.html"> Simple,
28 * Fast, and Practical Non-Blocking and Blocking Concurrent Queue
29 * Algorithms</a> by Maged M. Michael and Michael L. Scott.
30 *
31 * <p>Beware that, unlike in most collections, the {@code size} method
32 * is <em>NOT</em> a constant-time operation. Because of the
33 * asynchronous nature of these queues, determining the current number
34 * of elements requires a traversal of the elements.
35 *
36 * <p>This class and its iterator implement all of the
37 * <em>optional</em> methods of the {@link Collection} and {@link
38 * Iterator} interfaces.
39 *
40 * <p>Memory consistency effects: As with other concurrent
41 * collections, actions in a thread prior to placing an object into a
42 * {@code ConcurrentLinkedQueue}
43 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
44 * actions subsequent to the access or removal of that element from
45 * the {@code ConcurrentLinkedQueue} in another thread.
46 *
47 * <p>This class is a member of the
48 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
49 * Java Collections Framework</a>.
50 *
51 * @since 1.5
52 * @author Doug Lea
53 * @param <E> the type of elements held in this collection
54 *
55 */
56 public class ConcurrentLinkedQueue<E> extends AbstractQueue<E>
57 implements Queue<E>, java.io.Serializable {
58 private static final long serialVersionUID = 196745693267521676L;
59
60 /*
61 * This is a modification of the Michael & Scott algorithm,
62 * adapted for a garbage-collected environment, with support for
63 * interior node deletion (to support remove(Object)). For
64 * explanation, read the paper.
65 *
66 * Note that like most non-blocking algorithms in this package,
67 * this implementation relies on the fact that in garbage
68 * collected systems, there is no possibility of ABA problems due
69 * to recycled nodes, so there is no need to use "counted
70 * pointers" or related techniques seen in versions used in
71 * non-GC'ed settings.
72 *
73 * The fundamental invariants are:
74 * - There is exactly one (last) Node with a null next reference,
75 * which is CASed when enqueueing. This last Node can be
76 * reached in O(1) time from tail, but tail is merely an
77 * optimization - it can always be reached in O(N) time from
78 * head as well.
79 * - The elements contained in the queue are the non-null items in
80 * Nodes that are reachable from head. CASing the item
81 * reference of a Node to null atomically removes it from the
82 * queue. Reachability of all elements from head must remain
83 * true even in the case of concurrent modifications that cause
84 * head to advance. A dequeued Node may remain in use
85 * indefinitely due to creation of an Iterator or simply a
86 * poll() that has lost its time slice.
87 *
88 * The above might appear to imply that all Nodes are GC-reachable
89 * from a predecessor dequeued Node. That would cause two problems:
90 * - allow a rogue Iterator to cause unbounded memory retention
91 * - cause cross-generational linking of old Nodes to new Nodes if
92 * a Node was tenured while live, which generational GCs have a
93 * hard time dealing with, causing repeated major collections.
94 * However, only non-deleted Nodes need to be reachable from
95 * dequeued Nodes, and reachability does not necessarily have to
96 * be of the kind understood by the GC. We use the trick of
97 * linking a Node that has just been dequeued to itself. Such a
98 * self-link implicitly means to advance to head.
99 *
100 * Both head and tail are permitted to lag. In fact, failing to
101 * update them every time one could is a significant optimization
102 * (fewer CASes). This is controlled by local "hops" variables
103 * that only trigger helping-CASes after experiencing multiple
104 * lags.
105 *
106 * Since head and tail are updated concurrently and independently,
107 * it is possible for tail to lag behind head (why not)?
108 *
109 * CASing a Node's item reference to null atomically removes the
110 * element from the queue. Iterators skip over Nodes with null
111 * items. Prior implementations of this class had a race between
112 * poll() and remove(Object) where the same element would appear
113 * to be successfully removed by two concurrent operations. The
114 * method remove(Object) also lazily unlinks deleted Nodes, but
115 * this is merely an optimization.
116 *
117 * When constructing a Node (before enqueuing it) we avoid paying
118 * for a volatile write to item by using lazySet instead of a
119 * normal write. This allows the cost of enqueue to be
120 * "one-and-a-half" CASes.
121 *
122 * Both head and tail may or may not point to a Node with a
123 * non-null item. If the queue is empty, all items must of course
124 * be null. Upon creation, both head and tail refer to a dummy
125 * Node with null item. Both head and tail are only updated using
126 * CAS, so they never regress, although again this is merely an
127 * optimization.
128 */
129 private static class Node<E> {
130 private volatile E item;
131 private volatile Node<E> next;
132
133 private static final sun.misc.Unsafe unsafe = ConcurrentLinkedQueue.unsafe;
134 private static final long nextOffset = fieldOffset("next", Node.class);
135 private static final long itemOffset = fieldOffset("item", Node.class);
136
137
138 Node(E item) { lazySetItem(item); }
139
140 E getItem() {
141 return item;
142 }
143
144 boolean casItem(E cmp, E val) {
145 return unsafe.compareAndSwapObject(this, itemOffset, cmp, val);
146 }
147
148 void setItem(E val) {
149 item = val;
150 }
151
152 void lazySetItem(E val) {
153 unsafe.putOrderedObject(this, itemOffset, val);
154 }
155
156 void lazySetNext(Node<E> val) {
157 unsafe.putOrderedObject(this, nextOffset, val);
158 }
159
160 Node<E> getNext() {
161 return next;
162 }
163
164 boolean casNext(Node<E> cmp, Node<E> val) {
165 return unsafe.compareAndSwapObject(this, nextOffset, cmp, val);
166 }
167 }
168
169 private boolean casTail(Node<E> cmp, Node<E> val) {
170 return unsafe.compareAndSwapObject(this, tailOffset, cmp, val);
171 }
172
173 private boolean casHead(Node<E> cmp, Node<E> val) {
174 return unsafe.compareAndSwapObject(this, headOffset, cmp, val);
175 }
176
177 private void lazySetHead(Node<E> val) {
178 unsafe.putOrderedObject(this, headOffset, val);
179 }
180
181
182 /**
183 * Pointer to first node, initialized to a dummy node.
184 */
185 private transient volatile Node<E> head = new Node<E>(null);
186
187 /** Pointer to last node on list */
188 private transient volatile Node<E> tail = head;
189
190
191 /**
192 * Creates a {@code ConcurrentLinkedQueue} that is initially empty.
193 */
194 public ConcurrentLinkedQueue() {}
195
196 /**
197 * Creates a {@code ConcurrentLinkedQueue}
198 * initially containing the elements of the given collection,
199 * added in traversal order of the collection's iterator.
200 * @param c the collection of elements to initially contain
201 * @throws NullPointerException if the specified collection or any
202 * of its elements are null
203 */
204 public ConcurrentLinkedQueue(Collection<? extends E> c) {
205 for (Iterator<? extends E> it = c.iterator(); it.hasNext();)
206 add(it.next());
207 }
208
209 // Have to override just to update the javadoc
210
211 /**
212 * Inserts the specified element at the tail of this queue.
213 *
214 * @return {@code true} (as specified by {@link Collection#add})
215 * @throws NullPointerException if the specified element is null
216 */
217 public boolean add(E e) {
218 return offer(e);
219 }
220
221 /**
222 * We don't bother to update head or tail pointers if less than
223 * HOPS links from "true" location. We assume that volatile
224 * writes are significantly more expensive than volatile reads.
225 */
226 private static final int HOPS = 1;
227
228 /**
229 * Try to CAS head to p. If successful, repoint old head to itself
230 * as sentinel for succ(), below.
231 */
232 final void updateHead(Node<E> h, Node<E> p) {
233 if (h != p && casHead(h, p))
234 h.lazySetNext(h);
235 }
236
237 /**
238 * Returns the successor of p, or the head node if p.next has been
239 * linked to self, which will only be true if traversing with a
240 * stale pointer that is now off the list.
241 */
242 final Node<E> succ(Node<E> p) {
243 Node<E> next = p.getNext();
244 return (p == next) ? head : next;
245 }
246
247 /**
248 * Inserts the specified element at the tail of this queue.
249 *
250 * @return {@code true} (as specified by {@link Queue#offer})
251 * @throws NullPointerException if the specified element is null
252 */
253 public boolean offer(E e) {
254 if (e == null) throw new NullPointerException();
255 Node<E> n = new Node<E>(e);
256 retry:
257 for (;;) {
258 Node<E> t = tail;
259 Node<E> p = t;
260 for (int hops = 0; ; hops++) {
261 Node<E> next = succ(p);
262 if (next != null) {
263 if (hops > HOPS && t != tail)
264 continue retry;
265 p = next;
266 } else if (p.casNext(null, n)) {
267 if (hops >= HOPS)
268 casTail(t, n); // Failure is OK.
269 return true;
270 } else {
271 p = succ(p);
272 }
273 }
274 }
275 }
276
277 public E poll() {
278 Node<E> h = head;
279 Node<E> p = h;
280 for (int hops = 0; ; hops++) {
281 E item = p.getItem();
282
283 if (item != null && p.casItem(item, null)) {
284 if (hops >= HOPS) {
285 Node<E> q = p.getNext();
286 updateHead(h, (q != null) ? q : p);
287 }
288 return item;
289 }
290 Node<E> next = succ(p);
291 if (next == null) {
292 updateHead(h, p);
293 break;
294 }
295 p = next;
296 }
297 return null;
298 }
299
300 public E peek() {
301 Node<E> h = head;
302 Node<E> p = h;
303 E item;
304 for (;;) {
305 item = p.getItem();
306 if (item != null)
307 break;
308 Node<E> next = succ(p);
309 if (next == null) {
310 break;
311 }
312 p = next;
313 }
314 updateHead(h, p);
315 return item;
316 }
317
318 /**
319 * Returns the first actual (non-header) node on list. This is yet
320 * another variant of poll/peek; here returning out the first
321 * node, not element (so we cannot collapse with peek() without
322 * introducing race.)
323 */
324 Node<E> first() {
325 Node<E> h = head;
326 Node<E> p = h;
327 Node<E> result;
328 for (;;) {
329 E item = p.getItem();
330 if (item != null) {
331 result = p;
332 break;
333 }
334 Node<E> next = succ(p);
335 if (next == null) {
336 result = null;
337 break;
338 }
339 p = next;
340 }
341 updateHead(h, p);
342 return result;
343 }
344
345 /**
346 * Returns {@code true} if this queue contains no elements.
347 *
348 * @return {@code true} if this queue contains no elements
349 */
350 public boolean isEmpty() {
351 return first() == null;
352 }
353
354 /**
355 * Returns the number of elements in this queue. If this queue
356 * contains more than {@code Integer.MAX_VALUE} elements, returns
357 * {@code Integer.MAX_VALUE}.
358 *
359 * <p>Beware that, unlike in most collections, this method is
360 * <em>NOT</em> a constant-time operation. Because of the
361 * asynchronous nature of these queues, determining the current
362 * number of elements requires an O(n) traversal.
363 *
364 * @return the number of elements in this queue
365 */
366 public int size() {
367 int count = 0;
368 for (Node<E> p = first(); p != null; p = succ(p)) {
369 if (p.getItem() != null) {
370 // Collections.size() spec says to max out
371 if (++count == Integer.MAX_VALUE)
372 break;
373 }
374 }
375 return count;
376 }
377
378 /**
379 * Returns {@code true} if this queue contains the specified element.
380 * More formally, returns {@code true} if and only if this queue contains
381 * at least one element {@code e} such that {@code o.equals(e)}.
382 *
383 * @param o object to be checked for containment in this queue
384 * @return {@code true} if this queue contains the specified element
385 */
386 public boolean contains(Object o) {
387 if (o == null) return false;
388 for (Node<E> p = first(); p != null; p = succ(p)) {
389 E item = p.getItem();
390 if (item != null &&
391 o.equals(item))
392 return true;
393 }
394 return false;
395 }
396
397 /**
398 * Removes a single instance of the specified element from this queue,
399 * if it is present. More formally, removes an element {@code e} such
400 * that {@code o.equals(e)}, if this queue contains one or more such
401 * elements.
402 * Returns {@code true} if this queue contained the specified element
403 * (or equivalently, if this queue changed as a result of the call).
404 *
405 * @param o element to be removed from this queue, if present
406 * @return {@code true} if this queue changed as a result of the call
407 */
408 public boolean remove(Object o) {
409 if (o == null) return false;
410 Node<E> pred = null;
411 for (Node<E> p = first(); p != null; p = succ(p)) {
412 E item = p.getItem();
413 if (item != null && o.equals(item) && p.casItem(item, null)) {
414 Node<E> next = succ(p);
415 if (pred != null && next != null)
416 pred.casNext(p, next);
417 return true;
418 }
419 pred = p;
420 }
421 return false;
422 }
423
424 /**
425 * Returns an array containing all of the elements in this queue, in
426 * proper sequence.
427 *
428 * <p>The returned array will be "safe" in that no references to it are
429 * maintained by this queue. (In other words, this method must allocate
430 * a new array). The caller is thus free to modify the returned array.
431 *
432 * <p>This method acts as bridge between array-based and collection-based
433 * APIs.
434 *
435 * @return an array containing all of the elements in this queue
436 */
437 public Object[] toArray() {
438 // Use ArrayList to deal with resizing.
439 ArrayList<E> al = new ArrayList<E>();
440 for (Node<E> p = first(); p != null; p = succ(p)) {
441 E item = p.getItem();
442 if (item != null)
443 al.add(item);
444 }
445 return al.toArray();
446 }
447
448 /**
449 * Returns an array containing all of the elements in this queue, in
450 * proper sequence; the runtime type of the returned array is that of
451 * the specified array. If the queue fits in the specified array, it
452 * is returned therein. Otherwise, a new array is allocated with the
453 * runtime type of the specified array and the size of this queue.
454 *
455 * <p>If this queue fits in the specified array with room to spare
456 * (i.e., the array has more elements than this queue), the element in
457 * the array immediately following the end of the queue is set to
458 * {@code null}.
459 *
460 * <p>Like the {@link #toArray()} method, this method acts as bridge between
461 * array-based and collection-based APIs. Further, this method allows
462 * precise control over the runtime type of the output array, and may,
463 * under certain circumstances, be used to save allocation costs.
464 *
465 * <p>Suppose {@code x} is a queue known to contain only strings.
466 * The following code can be used to dump the queue into a newly
467 * allocated array of {@code String}:
468 *
469 * <pre>
470 * String[] y = x.toArray(new String[0]);</pre>
471 *
472 * Note that {@code toArray(new Object[0])} is identical in function to
473 * {@code toArray()}.
474 *
475 * @param a the array into which the elements of the queue are to
476 * be stored, if it is big enough; otherwise, a new array of the
477 * same runtime type is allocated for this purpose
478 * @return an array containing all of the elements in this queue
479 * @throws ArrayStoreException if the runtime type of the specified array
480 * is not a supertype of the runtime type of every element in
481 * this queue
482 * @throws NullPointerException if the specified array is null
483 */
484 @SuppressWarnings("unchecked")
485 public <T> T[] toArray(T[] a) {
486 // try to use sent-in array
487 int k = 0;
488 Node<E> p;
489 for (p = first(); p != null && k < a.length; p = succ(p)) {
490 E item = p.getItem();
491 if (item != null)
492 a[k++] = (T)item;
493 }
494 if (p == null) {
495 if (k < a.length)
496 a[k] = null;
497 return a;
498 }
499
500 // If won't fit, use ArrayList version
501 ArrayList<E> al = new ArrayList<E>();
502 for (Node<E> q = first(); q != null; q = succ(q)) {
503 E item = q.getItem();
504 if (item != null)
505 al.add(item);
506 }
507 return al.toArray(a);
508 }
509
510 /**
511 * Returns an iterator over the elements in this queue in proper sequence.
512 * The returned iterator is a "weakly consistent" iterator that
513 * will never throw {@link ConcurrentModificationException},
514 * and guarantees to traverse elements as they existed upon
515 * construction of the iterator, and may (but is not guaranteed to)
516 * reflect any modifications subsequent to construction.
517 *
518 * @return an iterator over the elements in this queue in proper sequence
519 */
520 public Iterator<E> iterator() {
521 return new Itr();
522 }
523
524 private class Itr implements Iterator<E> {
525 /**
526 * Next node to return item for.
527 */
528 private Node<E> nextNode;
529
530 /**
531 * nextItem holds on to item fields because once we claim
532 * that an element exists in hasNext(), we must return it in
533 * the following next() call even if it was in the process of
534 * being removed when hasNext() was called.
535 */
536 private E nextItem;
537
538 /**
539 * Node of the last returned item, to support remove.
540 */
541 private Node<E> lastRet;
542
543 Itr() {
544 advance();
545 }
546
547 /**
548 * Moves to next valid node and returns item to return for
549 * next(), or null if no such.
550 */
551 private E advance() {
552 lastRet = nextNode;
553 E x = nextItem;
554
555 Node<E> pred, p;
556 if (nextNode == null) {
557 p = first();
558 pred = null;
559 } else {
560 pred = nextNode;
561 p = succ(nextNode);
562 }
563
564 for (;;) {
565 if (p == null) {
566 nextNode = null;
567 nextItem = null;
568 return x;
569 }
570 E item = p.getItem();
571 if (item != null) {
572 nextNode = p;
573 nextItem = item;
574 return x;
575 } else {
576 // skip over nulls
577 Node<E> next = succ(p);
578 if (pred != null && next != null)
579 pred.casNext(p, next);
580 p = next;
581 }
582 }
583 }
584
585 public boolean hasNext() {
586 return nextNode != null;
587 }
588
589 public E next() {
590 if (nextNode == null) throw new NoSuchElementException();
591 return advance();
592 }
593
594 public void remove() {
595 Node<E> l = lastRet;
596 if (l == null) throw new IllegalStateException();
597 // rely on a future traversal to relink.
598 l.setItem(null);
599 lastRet = null;
600 }
601 }
602
603 /**
604 * Save the state to a stream (that is, serialize it).
605 *
606 * @serialData All of the elements (each an {@code E}) in
607 * the proper order, followed by a null
608 * @param s the stream
609 */
610 private void writeObject(java.io.ObjectOutputStream s)
611 throws java.io.IOException {
612
613 // Write out any hidden stuff
614 s.defaultWriteObject();
615
616 // Write out all elements in the proper order.
617 for (Node<E> p = first(); p != null; p = succ(p)) {
618 Object item = p.getItem();
619 if (item != null)
620 s.writeObject(item);
621 }
622
623 // Use trailing null as sentinel
624 s.writeObject(null);
625 }
626
627 /**
628 * Reconstitute the Queue instance from a stream (that is,
629 * deserialize it).
630 * @param s the stream
631 */
632 private void readObject(java.io.ObjectInputStream s)
633 throws java.io.IOException, ClassNotFoundException {
634 // Read in capacity, and any hidden stuff
635 s.defaultReadObject();
636 head = new Node<E>(null);
637 tail = head;
638 // Read in all elements and place in queue
639 for (;;) {
640 @SuppressWarnings("unchecked")
641 E item = (E)s.readObject();
642 if (item == null)
643 break;
644 else
645 offer(item);
646 }
647 }
648
649 // Unsafe mechanics
650 private static sun.misc.Unsafe getUnsafe() {
651 try {
652 return sun.misc.Unsafe.getUnsafe();
653 } catch (SecurityException se) {
654 try {
655 return java.security.AccessController.doPrivileged
656 (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() {
657 public sun.misc.Unsafe run() throws Exception {
658 return getUnsafeByReflection();
659 }});
660 } catch (java.security.PrivilegedActionException e) {
661 throw new RuntimeException("Could not initialize intrinsics",
662 e.getCause());
663 }
664 }
665 }
666
667 private static sun.misc.Unsafe getUnsafeByReflection()
668 throws NoSuchFieldException, IllegalAccessException {
669 java.lang.reflect.Field f = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
670 f.setAccessible(true);
671 return (sun.misc.Unsafe) f.get(null);
672 }
673
674 private static long fieldOffset(String fieldName, Class<?> klazz) {
675 try {
676 return unsafe.objectFieldOffset(klazz.getDeclaredField(fieldName));
677 } catch (NoSuchFieldException e) {
678 NoSuchFieldError error = new NoSuchFieldError(fieldName);
679 error.initCause(e);
680 throw error;
681 }
682 }
683
684 private static final sun.misc.Unsafe unsafe = getUnsafe();
685 private static final long headOffset =
686 fieldOffset("head", ConcurrentLinkedQueue.class);;
687 private static final long tailOffset =
688 fieldOffset("tail", ConcurrentLinkedQueue.class);
689 }