1 |
/* |
2 |
* Written by Doug Lea and Martin Buchholz with assistance from members of |
3 |
* JCP JSR-166 Expert Group and released to the public domain, as explained |
4 |
* at http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
|
9 |
import java.util.AbstractQueue; |
10 |
import java.util.ArrayList; |
11 |
import java.util.Collection; |
12 |
import java.util.Iterator; |
13 |
import java.util.NoSuchElementException; |
14 |
import java.util.Queue; |
15 |
import java.util.Spliterator; |
16 |
import java.util.Spliterators; |
17 |
import java.util.function.Consumer; |
18 |
|
19 |
/** |
20 |
* An unbounded thread-safe {@linkplain Queue queue} based on linked nodes. |
21 |
* This queue orders elements FIFO (first-in-first-out). |
22 |
* The <em>head</em> of the queue is that element that has been on the |
23 |
* queue the longest time. |
24 |
* The <em>tail</em> of the queue is that element that has been on the |
25 |
* queue the shortest time. New elements |
26 |
* are inserted at the tail of the queue, and the queue retrieval |
27 |
* operations obtain elements at the head of the queue. |
28 |
* A {@code ConcurrentLinkedQueue} is an appropriate choice when |
29 |
* many threads will share access to a common collection. |
30 |
* Like most other concurrent collection implementations, this class |
31 |
* does not permit the use of {@code null} elements. |
32 |
* |
33 |
* <p>This implementation employs an efficient <em>non-blocking</em> |
34 |
* algorithm based on one described in |
35 |
* <a href="http://www.cs.rochester.edu/~scott/papers/1996_PODC_queues.pdf"> |
36 |
* Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue |
37 |
* Algorithms</a> by Maged M. Michael and Michael L. Scott. |
38 |
* |
39 |
* <p>Iterators are <i>weakly consistent</i>, returning elements |
40 |
* reflecting the state of the queue at some point at or since the |
41 |
* creation of the iterator. They do <em>not</em> throw {@link |
42 |
* java.util.ConcurrentModificationException}, and may proceed concurrently |
43 |
* with other operations. Elements contained in the queue since the creation |
44 |
* of the iterator will be returned exactly once. |
45 |
* |
46 |
* <p>Beware that, unlike in most collections, the {@code size} method |
47 |
* is <em>NOT</em> a constant-time operation. Because of the |
48 |
* asynchronous nature of these queues, determining the current number |
49 |
* of elements requires a traversal of the elements, and so may report |
50 |
* inaccurate results if this collection is modified during traversal. |
51 |
* Additionally, the bulk operations {@code addAll}, |
52 |
* {@code removeAll}, {@code retainAll}, {@code containsAll}, |
53 |
* {@code equals}, and {@code toArray} are <em>not</em> guaranteed |
54 |
* to be performed atomically. For example, an iterator operating |
55 |
* concurrently with an {@code addAll} operation might view only some |
56 |
* of the added elements. |
57 |
* |
58 |
* <p>This class and its iterator implement all of the <em>optional</em> |
59 |
* methods of the {@link Queue} and {@link Iterator} interfaces. |
60 |
* |
61 |
* <p>Memory consistency effects: As with other concurrent |
62 |
* collections, actions in a thread prior to placing an object into a |
63 |
* {@code ConcurrentLinkedQueue} |
64 |
* <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> |
65 |
* actions subsequent to the access or removal of that element from |
66 |
* the {@code ConcurrentLinkedQueue} in another thread. |
67 |
* |
68 |
* <p>This class is a member of the |
69 |
* <a href="{@docRoot}/../technotes/guides/collections/index.html"> |
70 |
* Java Collections Framework</a>. |
71 |
* |
72 |
* @since 1.5 |
73 |
* @author Doug Lea |
74 |
* @param <E> the type of elements held in this queue |
75 |
*/ |
76 |
public class ConcurrentLinkedQueue<E> extends AbstractQueue<E> |
77 |
implements Queue<E>, java.io.Serializable { |
78 |
private static final long serialVersionUID = 196745693267521676L; |
79 |
|
80 |
/* |
81 |
* This is a modification of the Michael & Scott algorithm, |
82 |
* adapted for a garbage-collected environment, with support for |
83 |
* interior node deletion (to support remove(Object)). For |
84 |
* explanation, read the paper. |
85 |
* |
86 |
* Note that like most non-blocking algorithms in this package, |
87 |
* this implementation relies on the fact that in garbage |
88 |
* collected systems, there is no possibility of ABA problems due |
89 |
* to recycled nodes, so there is no need to use "counted |
90 |
* pointers" or related techniques seen in versions used in |
91 |
* non-GC'ed settings. |
92 |
* |
93 |
* The fundamental invariants are: |
94 |
* - There is exactly one (last) Node with a null next reference, |
95 |
* which is CASed when enqueueing. This last Node can be |
96 |
* reached in O(1) time from tail, but tail is merely an |
97 |
* optimization - it can always be reached in O(N) time from |
98 |
* head as well. |
99 |
* - The elements contained in the queue are the non-null items in |
100 |
* Nodes that are reachable from head. CASing the item |
101 |
* reference of a Node to null atomically removes it from the |
102 |
* queue. Reachability of all elements from head must remain |
103 |
* true even in the case of concurrent modifications that cause |
104 |
* head to advance. A dequeued Node may remain in use |
105 |
* indefinitely due to creation of an Iterator or simply a |
106 |
* poll() that has lost its time slice. |
107 |
* |
108 |
* The above might appear to imply that all Nodes are GC-reachable |
109 |
* from a predecessor dequeued Node. That would cause two problems: |
110 |
* - allow a rogue Iterator to cause unbounded memory retention |
111 |
* - cause cross-generational linking of old Nodes to new Nodes if |
112 |
* a Node was tenured while live, which generational GCs have a |
113 |
* hard time dealing with, causing repeated major collections. |
114 |
* However, only non-deleted Nodes need to be reachable from |
115 |
* dequeued Nodes, and reachability does not necessarily have to |
116 |
* be of the kind understood by the GC. We use the trick of |
117 |
* linking a Node that has just been dequeued to itself. Such a |
118 |
* self-link implicitly means to advance to head. |
119 |
* |
120 |
* Both head and tail are permitted to lag. In fact, failing to |
121 |
* update them every time one could is a significant optimization |
122 |
* (fewer CASes). As with LinkedTransferQueue (see the internal |
123 |
* documentation for that class), we use a slack threshold of two; |
124 |
* that is, we update head/tail when the current pointer appears |
125 |
* to be two or more steps away from the first/last node. |
126 |
* |
127 |
* Since head and tail are updated concurrently and independently, |
128 |
* it is possible for tail to lag behind head (why not)? |
129 |
* |
130 |
* CASing a Node's item reference to null atomically removes the |
131 |
* element from the queue. Iterators skip over Nodes with null |
132 |
* items. Prior implementations of this class had a race between |
133 |
* poll() and remove(Object) where the same element would appear |
134 |
* to be successfully removed by two concurrent operations. The |
135 |
* method remove(Object) also lazily unlinks deleted Nodes, but |
136 |
* this is merely an optimization. |
137 |
* |
138 |
* When constructing a Node (before enqueuing it) we avoid paying |
139 |
* for a volatile write to item by using Unsafe.putObject instead |
140 |
* of a normal write. This allows the cost of enqueue to be |
141 |
* "one-and-a-half" CASes. |
142 |
* |
143 |
* Both head and tail may or may not point to a Node with a |
144 |
* non-null item. If the queue is empty, all items must of course |
145 |
* be null. Upon creation, both head and tail refer to a dummy |
146 |
* Node with null item. Both head and tail are only updated using |
147 |
* CAS, so they never regress, although again this is merely an |
148 |
* optimization. |
149 |
*/ |
150 |
|
151 |
private static class Node<E> { |
152 |
volatile E item; |
153 |
volatile Node<E> next; |
154 |
} |
155 |
|
156 |
/** |
157 |
* Returns a new node holding item. Uses relaxed write because item |
158 |
* can only be seen after piggy-backing publication via casNext. |
159 |
*/ |
160 |
static <E> Node<E> newNode(E item) { |
161 |
Node<E> node = new Node<E>(); |
162 |
U.putObject(node, ITEM, item); |
163 |
return node; |
164 |
} |
165 |
|
166 |
static <E> boolean casItem(Node<E> node, E cmp, E val) { |
167 |
return U.compareAndSwapObject(node, ITEM, cmp, val); |
168 |
} |
169 |
|
170 |
static <E> void lazySetNext(Node<E> node, Node<E> val) { |
171 |
U.putOrderedObject(node, NEXT, val); |
172 |
} |
173 |
|
174 |
static <E> boolean casNext(Node<E> node, Node<E> cmp, Node<E> val) { |
175 |
return U.compareAndSwapObject(node, NEXT, cmp, val); |
176 |
} |
177 |
|
178 |
/** |
179 |
* A node from which the first live (non-deleted) node (if any) |
180 |
* can be reached in O(1) time. |
181 |
* Invariants: |
182 |
* - all live nodes are reachable from head via succ() |
183 |
* - head != null |
184 |
* - (tmp = head).next != tmp || tmp != head |
185 |
* Non-invariants: |
186 |
* - head.item may or may not be null. |
187 |
* - it is permitted for tail to lag behind head, that is, for tail |
188 |
* to not be reachable from head! |
189 |
*/ |
190 |
private transient volatile Node<E> head; |
191 |
|
192 |
/** |
193 |
* A node from which the last node on list (that is, the unique |
194 |
* node with node.next == null) can be reached in O(1) time. |
195 |
* Invariants: |
196 |
* - the last node is always reachable from tail via succ() |
197 |
* - tail != null |
198 |
* Non-invariants: |
199 |
* - tail.item may or may not be null. |
200 |
* - it is permitted for tail to lag behind head, that is, for tail |
201 |
* to not be reachable from head! |
202 |
* - tail.next may or may not be self-pointing to tail. |
203 |
*/ |
204 |
private transient volatile Node<E> tail; |
205 |
|
206 |
/** |
207 |
* Creates a {@code ConcurrentLinkedQueue} that is initially empty. |
208 |
*/ |
209 |
public ConcurrentLinkedQueue() { |
210 |
head = tail = newNode(null); |
211 |
} |
212 |
|
213 |
/** |
214 |
* Creates a {@code ConcurrentLinkedQueue} |
215 |
* initially containing the elements of the given collection, |
216 |
* added in traversal order of the collection's iterator. |
217 |
* |
218 |
* @param c the collection of elements to initially contain |
219 |
* @throws NullPointerException if the specified collection or any |
220 |
* of its elements are null |
221 |
*/ |
222 |
public ConcurrentLinkedQueue(Collection<? extends E> c) { |
223 |
Node<E> h = null, t = null; |
224 |
for (E e : c) { |
225 |
checkNotNull(e); |
226 |
Node<E> newNode = newNode(e); |
227 |
if (h == null) |
228 |
h = t = newNode; |
229 |
else { |
230 |
lazySetNext(t, newNode); |
231 |
t = newNode; |
232 |
} |
233 |
} |
234 |
if (h == null) |
235 |
h = t = newNode(null); |
236 |
head = h; |
237 |
tail = t; |
238 |
} |
239 |
|
240 |
// Have to override just to update the javadoc |
241 |
|
242 |
/** |
243 |
* Inserts the specified element at the tail of this queue. |
244 |
* As the queue is unbounded, this method will never throw |
245 |
* {@link IllegalStateException} or return {@code false}. |
246 |
* |
247 |
* @return {@code true} (as specified by {@link Collection#add}) |
248 |
* @throws NullPointerException if the specified element is null |
249 |
*/ |
250 |
public boolean add(E e) { |
251 |
return offer(e); |
252 |
} |
253 |
|
254 |
/** |
255 |
* Tries to CAS head to p. If successful, repoint old head to itself |
256 |
* as sentinel for succ(), below. |
257 |
*/ |
258 |
final void updateHead(Node<E> h, Node<E> p) { |
259 |
// assert h != null && p != null && (h == p || h.item == null); |
260 |
if (h != p && casHead(h, p)) |
261 |
lazySetNext(h, h); |
262 |
} |
263 |
|
264 |
/** |
265 |
* Returns the successor of p, or the head node if p.next has been |
266 |
* linked to self, which will only be true if traversing with a |
267 |
* stale pointer that is now off the list. |
268 |
*/ |
269 |
final Node<E> succ(Node<E> p) { |
270 |
Node<E> next = p.next; |
271 |
return (p == next) ? head : next; |
272 |
} |
273 |
|
274 |
/** |
275 |
* Inserts the specified element at the tail of this queue. |
276 |
* As the queue is unbounded, this method will never return {@code false}. |
277 |
* |
278 |
* @return {@code true} (as specified by {@link Queue#offer}) |
279 |
* @throws NullPointerException if the specified element is null |
280 |
*/ |
281 |
public boolean offer(E e) { |
282 |
checkNotNull(e); |
283 |
final Node<E> newNode = newNode(e); |
284 |
|
285 |
for (Node<E> t = tail, p = t;;) { |
286 |
Node<E> q = p.next; |
287 |
if (q == null) { |
288 |
// p is last node |
289 |
if (casNext(p, null, newNode)) { |
290 |
// Successful CAS is the linearization point |
291 |
// for e to become an element of this queue, |
292 |
// and for newNode to become "live". |
293 |
if (p != t) // hop two nodes at a time |
294 |
casTail(t, newNode); // Failure is OK. |
295 |
return true; |
296 |
} |
297 |
// Lost CAS race to another thread; re-read next |
298 |
} |
299 |
else if (p == q) |
300 |
// We have fallen off list. If tail is unchanged, it |
301 |
// will also be off-list, in which case we need to |
302 |
// jump to head, from which all live nodes are always |
303 |
// reachable. Else the new tail is a better bet. |
304 |
p = (t != (t = tail)) ? t : head; |
305 |
else |
306 |
// Check for tail updates after two hops. |
307 |
p = (p != t && t != (t = tail)) ? t : q; |
308 |
} |
309 |
} |
310 |
|
311 |
public E poll() { |
312 |
restartFromHead: |
313 |
for (;;) { |
314 |
for (Node<E> h = head, p = h, q;;) { |
315 |
E item = p.item; |
316 |
|
317 |
if (item != null && casItem(p, item, null)) { |
318 |
// Successful CAS is the linearization point |
319 |
// for item to be removed from this queue. |
320 |
if (p != h) // hop two nodes at a time |
321 |
updateHead(h, ((q = p.next) != null) ? q : p); |
322 |
return item; |
323 |
} |
324 |
else if ((q = p.next) == null) { |
325 |
updateHead(h, p); |
326 |
return null; |
327 |
} |
328 |
else if (p == q) |
329 |
continue restartFromHead; |
330 |
else |
331 |
p = q; |
332 |
} |
333 |
} |
334 |
} |
335 |
|
336 |
public E peek() { |
337 |
restartFromHead: |
338 |
for (;;) { |
339 |
for (Node<E> h = head, p = h, q;;) { |
340 |
E item = p.item; |
341 |
if (item != null || (q = p.next) == null) { |
342 |
updateHead(h, p); |
343 |
return item; |
344 |
} |
345 |
else if (p == q) |
346 |
continue restartFromHead; |
347 |
else |
348 |
p = q; |
349 |
} |
350 |
} |
351 |
} |
352 |
|
353 |
/** |
354 |
* Returns the first live (non-deleted) node on list, or null if none. |
355 |
* This is yet another variant of poll/peek; here returning the |
356 |
* first node, not element. We could make peek() a wrapper around |
357 |
* first(), but that would cost an extra volatile read of item, |
358 |
* and the need to add a retry loop to deal with the possibility |
359 |
* of losing a race to a concurrent poll(). |
360 |
*/ |
361 |
Node<E> first() { |
362 |
restartFromHead: |
363 |
for (;;) { |
364 |
for (Node<E> h = head, p = h, q;;) { |
365 |
boolean hasItem = (p.item != null); |
366 |
if (hasItem || (q = p.next) == null) { |
367 |
updateHead(h, p); |
368 |
return hasItem ? p : null; |
369 |
} |
370 |
else if (p == q) |
371 |
continue restartFromHead; |
372 |
else |
373 |
p = q; |
374 |
} |
375 |
} |
376 |
} |
377 |
|
378 |
/** |
379 |
* Returns {@code true} if this queue contains no elements. |
380 |
* |
381 |
* @return {@code true} if this queue contains no elements |
382 |
*/ |
383 |
public boolean isEmpty() { |
384 |
return first() == null; |
385 |
} |
386 |
|
387 |
/** |
388 |
* Returns the number of elements in this queue. If this queue |
389 |
* contains more than {@code Integer.MAX_VALUE} elements, returns |
390 |
* {@code Integer.MAX_VALUE}. |
391 |
* |
392 |
* <p>Beware that, unlike in most collections, this method is |
393 |
* <em>NOT</em> a constant-time operation. Because of the |
394 |
* asynchronous nature of these queues, determining the current |
395 |
* number of elements requires an O(n) traversal. |
396 |
* Additionally, if elements are added or removed during execution |
397 |
* of this method, the returned result may be inaccurate. Thus, |
398 |
* this method is typically not very useful in concurrent |
399 |
* applications. |
400 |
* |
401 |
* @return the number of elements in this queue |
402 |
*/ |
403 |
public int size() { |
404 |
restartFromHead: for (;;) { |
405 |
int count = 0; |
406 |
for (Node<E> p = first(); p != null;) { |
407 |
if (p.item != null) |
408 |
if (++count == Integer.MAX_VALUE) |
409 |
break; // @see Collection.size() |
410 |
Node<E> next = p.next; |
411 |
if (p == next) |
412 |
continue restartFromHead; |
413 |
p = next; |
414 |
} |
415 |
return count; |
416 |
} |
417 |
} |
418 |
|
419 |
/** |
420 |
* Returns {@code true} if this queue contains the specified element. |
421 |
* More formally, returns {@code true} if and only if this queue contains |
422 |
* at least one element {@code e} such that {@code o.equals(e)}. |
423 |
* |
424 |
* @param o object to be checked for containment in this queue |
425 |
* @return {@code true} if this queue contains the specified element |
426 |
*/ |
427 |
public boolean contains(Object o) { |
428 |
if (o != null) { |
429 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
430 |
E item = p.item; |
431 |
if (item != null && o.equals(item)) |
432 |
return true; |
433 |
} |
434 |
} |
435 |
return false; |
436 |
} |
437 |
|
438 |
/** |
439 |
* Removes a single instance of the specified element from this queue, |
440 |
* if it is present. More formally, removes an element {@code e} such |
441 |
* that {@code o.equals(e)}, if this queue contains one or more such |
442 |
* elements. |
443 |
* Returns {@code true} if this queue contained the specified element |
444 |
* (or equivalently, if this queue changed as a result of the call). |
445 |
* |
446 |
* @param o element to be removed from this queue, if present |
447 |
* @return {@code true} if this queue changed as a result of the call |
448 |
*/ |
449 |
public boolean remove(Object o) { |
450 |
if (o != null) { |
451 |
Node<E> next, pred = null; |
452 |
for (Node<E> p = first(); p != null; pred = p, p = next) { |
453 |
boolean removed = false; |
454 |
E item = p.item; |
455 |
if (item != null) { |
456 |
if (!o.equals(item)) { |
457 |
next = succ(p); |
458 |
continue; |
459 |
} |
460 |
removed = casItem(p, item, null); |
461 |
} |
462 |
|
463 |
next = succ(p); |
464 |
if (pred != null && next != null) // unlink |
465 |
casNext(pred, p, next); |
466 |
if (removed) |
467 |
return true; |
468 |
} |
469 |
} |
470 |
return false; |
471 |
} |
472 |
|
473 |
/** |
474 |
* Appends all of the elements in the specified collection to the end of |
475 |
* this queue, in the order that they are returned by the specified |
476 |
* collection's iterator. Attempts to {@code addAll} of a queue to |
477 |
* itself result in {@code IllegalArgumentException}. |
478 |
* |
479 |
* @param c the elements to be inserted into this queue |
480 |
* @return {@code true} if this queue changed as a result of the call |
481 |
* @throws NullPointerException if the specified collection or any |
482 |
* of its elements are null |
483 |
* @throws IllegalArgumentException if the collection is this queue |
484 |
*/ |
485 |
public boolean addAll(Collection<? extends E> c) { |
486 |
if (c == this) |
487 |
// As historically specified in AbstractQueue#addAll |
488 |
throw new IllegalArgumentException(); |
489 |
|
490 |
// Copy c into a private chain of Nodes |
491 |
Node<E> beginningOfTheEnd = null, last = null; |
492 |
for (E e : c) { |
493 |
checkNotNull(e); |
494 |
Node<E> newNode = newNode(e); |
495 |
if (beginningOfTheEnd == null) |
496 |
beginningOfTheEnd = last = newNode; |
497 |
else { |
498 |
lazySetNext(last, newNode); |
499 |
last = newNode; |
500 |
} |
501 |
} |
502 |
if (beginningOfTheEnd == null) |
503 |
return false; |
504 |
|
505 |
// Atomically append the chain at the tail of this collection |
506 |
for (Node<E> t = tail, p = t;;) { |
507 |
Node<E> q = p.next; |
508 |
if (q == null) { |
509 |
// p is last node |
510 |
if (casNext(p, null, beginningOfTheEnd)) { |
511 |
// Successful CAS is the linearization point |
512 |
// for all elements to be added to this queue. |
513 |
if (!casTail(t, last)) { |
514 |
// Try a little harder to update tail, |
515 |
// since we may be adding many elements. |
516 |
t = tail; |
517 |
if (last.next == null) |
518 |
casTail(t, last); |
519 |
} |
520 |
return true; |
521 |
} |
522 |
// Lost CAS race to another thread; re-read next |
523 |
} |
524 |
else if (p == q) |
525 |
// We have fallen off list. If tail is unchanged, it |
526 |
// will also be off-list, in which case we need to |
527 |
// jump to head, from which all live nodes are always |
528 |
// reachable. Else the new tail is a better bet. |
529 |
p = (t != (t = tail)) ? t : head; |
530 |
else |
531 |
// Check for tail updates after two hops. |
532 |
p = (p != t && t != (t = tail)) ? t : q; |
533 |
} |
534 |
} |
535 |
|
536 |
/** |
537 |
* Returns an array containing all of the elements in this queue, in |
538 |
* proper sequence. |
539 |
* |
540 |
* <p>The returned array will be "safe" in that no references to it are |
541 |
* maintained by this queue. (In other words, this method must allocate |
542 |
* a new array). The caller is thus free to modify the returned array. |
543 |
* |
544 |
* <p>This method acts as bridge between array-based and collection-based |
545 |
* APIs. |
546 |
* |
547 |
* @return an array containing all of the elements in this queue |
548 |
*/ |
549 |
public Object[] toArray() { |
550 |
// Use ArrayList to deal with resizing. |
551 |
ArrayList<E> al = new ArrayList<E>(); |
552 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
553 |
E item = p.item; |
554 |
if (item != null) |
555 |
al.add(item); |
556 |
} |
557 |
return al.toArray(); |
558 |
} |
559 |
|
560 |
/** |
561 |
* Returns an array containing all of the elements in this queue, in |
562 |
* proper sequence; the runtime type of the returned array is that of |
563 |
* the specified array. If the queue fits in the specified array, it |
564 |
* is returned therein. Otherwise, a new array is allocated with the |
565 |
* runtime type of the specified array and the size of this queue. |
566 |
* |
567 |
* <p>If this queue fits in the specified array with room to spare |
568 |
* (i.e., the array has more elements than this queue), the element in |
569 |
* the array immediately following the end of the queue is set to |
570 |
* {@code null}. |
571 |
* |
572 |
* <p>Like the {@link #toArray()} method, this method acts as bridge between |
573 |
* array-based and collection-based APIs. Further, this method allows |
574 |
* precise control over the runtime type of the output array, and may, |
575 |
* under certain circumstances, be used to save allocation costs. |
576 |
* |
577 |
* <p>Suppose {@code x} is a queue known to contain only strings. |
578 |
* The following code can be used to dump the queue into a newly |
579 |
* allocated array of {@code String}: |
580 |
* |
581 |
* <pre> {@code String[] y = x.toArray(new String[0]);}</pre> |
582 |
* |
583 |
* Note that {@code toArray(new Object[0])} is identical in function to |
584 |
* {@code toArray()}. |
585 |
* |
586 |
* @param a the array into which the elements of the queue are to |
587 |
* be stored, if it is big enough; otherwise, a new array of the |
588 |
* same runtime type is allocated for this purpose |
589 |
* @return an array containing all of the elements in this queue |
590 |
* @throws ArrayStoreException if the runtime type of the specified array |
591 |
* is not a supertype of the runtime type of every element in |
592 |
* this queue |
593 |
* @throws NullPointerException if the specified array is null |
594 |
*/ |
595 |
@SuppressWarnings("unchecked") |
596 |
public <T> T[] toArray(T[] a) { |
597 |
// try to use sent-in array |
598 |
int k = 0; |
599 |
Node<E> p; |
600 |
for (p = first(); p != null && k < a.length; p = succ(p)) { |
601 |
E item = p.item; |
602 |
if (item != null) |
603 |
a[k++] = (T)item; |
604 |
} |
605 |
if (p == null) { |
606 |
if (k < a.length) |
607 |
a[k] = null; |
608 |
return a; |
609 |
} |
610 |
|
611 |
// If won't fit, use ArrayList version |
612 |
ArrayList<E> al = new ArrayList<E>(); |
613 |
for (Node<E> q = first(); q != null; q = succ(q)) { |
614 |
E item = q.item; |
615 |
if (item != null) |
616 |
al.add(item); |
617 |
} |
618 |
return al.toArray(a); |
619 |
} |
620 |
|
621 |
/** |
622 |
* Returns an iterator over the elements in this queue in proper sequence. |
623 |
* The elements will be returned in order from first (head) to last (tail). |
624 |
* |
625 |
* <p>The returned iterator is |
626 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
627 |
* |
628 |
* @return an iterator over the elements in this queue in proper sequence |
629 |
*/ |
630 |
public Iterator<E> iterator() { |
631 |
return new Itr(); |
632 |
} |
633 |
|
634 |
private class Itr implements Iterator<E> { |
635 |
/** |
636 |
* Next node to return item for. |
637 |
*/ |
638 |
private Node<E> nextNode; |
639 |
|
640 |
/** |
641 |
* nextItem holds on to item fields because once we claim |
642 |
* that an element exists in hasNext(), we must return it in |
643 |
* the following next() call even if it was in the process of |
644 |
* being removed when hasNext() was called. |
645 |
*/ |
646 |
private E nextItem; |
647 |
|
648 |
/** |
649 |
* Node of the last returned item, to support remove. |
650 |
*/ |
651 |
private Node<E> lastRet; |
652 |
|
653 |
Itr() { |
654 |
advance(); |
655 |
} |
656 |
|
657 |
/** |
658 |
* Moves to next valid node. |
659 |
*/ |
660 |
private void advance() { |
661 |
lastRet = nextNode; |
662 |
|
663 |
final Node<E> pred = nextNode; |
664 |
|
665 |
for (Node<E> p = (pred == null) ? first() : succ(pred);;) { |
666 |
if (p == null) { |
667 |
nextNode = null; |
668 |
nextItem = null; |
669 |
break; |
670 |
} |
671 |
E item = p.item; |
672 |
if (item != null) { |
673 |
nextNode = p; |
674 |
nextItem = item; |
675 |
break; |
676 |
} else { |
677 |
// skip over nulls |
678 |
Node<E> next = succ(p); |
679 |
if (pred != null && next != null) |
680 |
casNext(pred, p, next); |
681 |
p = next; |
682 |
} |
683 |
} |
684 |
} |
685 |
|
686 |
public boolean hasNext() { |
687 |
return nextItem != null; |
688 |
} |
689 |
|
690 |
public E next() { |
691 |
E x = nextItem; |
692 |
if (x == null) throw new NoSuchElementException(); |
693 |
advance(); |
694 |
return x; |
695 |
} |
696 |
|
697 |
public void remove() { |
698 |
Node<E> l = lastRet; |
699 |
if (l == null) throw new IllegalStateException(); |
700 |
// rely on a future traversal to relink. |
701 |
l.item = null; |
702 |
lastRet = null; |
703 |
} |
704 |
} |
705 |
|
706 |
/** |
707 |
* Saves this queue to a stream (that is, serializes it). |
708 |
* |
709 |
* @param s the stream |
710 |
* @throws java.io.IOException if an I/O error occurs |
711 |
* @serialData All of the elements (each an {@code E}) in |
712 |
* the proper order, followed by a null |
713 |
*/ |
714 |
private void writeObject(java.io.ObjectOutputStream s) |
715 |
throws java.io.IOException { |
716 |
|
717 |
// Write out any hidden stuff |
718 |
s.defaultWriteObject(); |
719 |
|
720 |
// Write out all elements in the proper order. |
721 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
722 |
Object item = p.item; |
723 |
if (item != null) |
724 |
s.writeObject(item); |
725 |
} |
726 |
|
727 |
// Use trailing null as sentinel |
728 |
s.writeObject(null); |
729 |
} |
730 |
|
731 |
/** |
732 |
* Reconstitutes this queue from a stream (that is, deserializes it). |
733 |
* @param s the stream |
734 |
* @throws ClassNotFoundException if the class of a serialized object |
735 |
* could not be found |
736 |
* @throws java.io.IOException if an I/O error occurs |
737 |
*/ |
738 |
private void readObject(java.io.ObjectInputStream s) |
739 |
throws java.io.IOException, ClassNotFoundException { |
740 |
s.defaultReadObject(); |
741 |
|
742 |
// Read in elements until trailing null sentinel found |
743 |
Node<E> h = null, t = null; |
744 |
for (Object item; (item = s.readObject()) != null; ) { |
745 |
@SuppressWarnings("unchecked") |
746 |
Node<E> newNode = newNode((E) item); |
747 |
if (h == null) |
748 |
h = t = newNode; |
749 |
else { |
750 |
lazySetNext(t, newNode); |
751 |
t = newNode; |
752 |
} |
753 |
} |
754 |
if (h == null) |
755 |
h = t = newNode(null); |
756 |
head = h; |
757 |
tail = t; |
758 |
} |
759 |
|
760 |
/** A customized variant of Spliterators.IteratorSpliterator */ |
761 |
static final class CLQSpliterator<E> implements Spliterator<E> { |
762 |
static final int MAX_BATCH = 1 << 25; // max batch array size; |
763 |
final ConcurrentLinkedQueue<E> queue; |
764 |
Node<E> current; // current node; null until initialized |
765 |
int batch; // batch size for splits |
766 |
boolean exhausted; // true when no more nodes |
767 |
CLQSpliterator(ConcurrentLinkedQueue<E> queue) { |
768 |
this.queue = queue; |
769 |
} |
770 |
|
771 |
public Spliterator<E> trySplit() { |
772 |
Node<E> p; |
773 |
final ConcurrentLinkedQueue<E> q = this.queue; |
774 |
int b = batch; |
775 |
int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1; |
776 |
if (!exhausted && |
777 |
((p = current) != null || (p = q.first()) != null) && |
778 |
p.next != null) { |
779 |
Object[] a = new Object[n]; |
780 |
int i = 0; |
781 |
do { |
782 |
if ((a[i] = p.item) != null) |
783 |
++i; |
784 |
if (p == (p = p.next)) |
785 |
p = q.first(); |
786 |
} while (p != null && i < n); |
787 |
if ((current = p) == null) |
788 |
exhausted = true; |
789 |
if (i > 0) { |
790 |
batch = i; |
791 |
return Spliterators.spliterator |
792 |
(a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL | |
793 |
Spliterator.CONCURRENT); |
794 |
} |
795 |
} |
796 |
return null; |
797 |
} |
798 |
|
799 |
public void forEachRemaining(Consumer<? super E> action) { |
800 |
Node<E> p; |
801 |
if (action == null) throw new NullPointerException(); |
802 |
final ConcurrentLinkedQueue<E> q = this.queue; |
803 |
if (!exhausted && |
804 |
((p = current) != null || (p = q.first()) != null)) { |
805 |
exhausted = true; |
806 |
do { |
807 |
E e = p.item; |
808 |
if (p == (p = p.next)) |
809 |
p = q.first(); |
810 |
if (e != null) |
811 |
action.accept(e); |
812 |
} while (p != null); |
813 |
} |
814 |
} |
815 |
|
816 |
public boolean tryAdvance(Consumer<? super E> action) { |
817 |
Node<E> p; |
818 |
if (action == null) throw new NullPointerException(); |
819 |
final ConcurrentLinkedQueue<E> q = this.queue; |
820 |
if (!exhausted && |
821 |
((p = current) != null || (p = q.first()) != null)) { |
822 |
E e; |
823 |
do { |
824 |
e = p.item; |
825 |
if (p == (p = p.next)) |
826 |
p = q.first(); |
827 |
} while (e == null && p != null); |
828 |
if ((current = p) == null) |
829 |
exhausted = true; |
830 |
if (e != null) { |
831 |
action.accept(e); |
832 |
return true; |
833 |
} |
834 |
} |
835 |
return false; |
836 |
} |
837 |
|
838 |
public long estimateSize() { return Long.MAX_VALUE; } |
839 |
|
840 |
public int characteristics() { |
841 |
return Spliterator.ORDERED | Spliterator.NONNULL | |
842 |
Spliterator.CONCURRENT; |
843 |
} |
844 |
} |
845 |
|
846 |
/** |
847 |
* Returns a {@link Spliterator} over the elements in this queue. |
848 |
* |
849 |
* <p>The returned spliterator is |
850 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
851 |
* |
852 |
* <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT}, |
853 |
* {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}. |
854 |
* |
855 |
* @implNote |
856 |
* The {@code Spliterator} implements {@code trySplit} to permit limited |
857 |
* parallelism. |
858 |
* |
859 |
* @return a {@code Spliterator} over the elements in this queue |
860 |
* @since 1.8 |
861 |
*/ |
862 |
@Override |
863 |
public Spliterator<E> spliterator() { |
864 |
return new CLQSpliterator<E>(this); |
865 |
} |
866 |
|
867 |
/** |
868 |
* Throws NullPointerException if argument is null. |
869 |
* |
870 |
* @param v the element |
871 |
*/ |
872 |
private static void checkNotNull(Object v) { |
873 |
if (v == null) |
874 |
throw new NullPointerException(); |
875 |
} |
876 |
|
877 |
private boolean casTail(Node<E> cmp, Node<E> val) { |
878 |
return U.compareAndSwapObject(this, TAIL, cmp, val); |
879 |
} |
880 |
|
881 |
private boolean casHead(Node<E> cmp, Node<E> val) { |
882 |
return U.compareAndSwapObject(this, HEAD, cmp, val); |
883 |
} |
884 |
|
885 |
// Unsafe mechanics |
886 |
|
887 |
private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe(); |
888 |
private static final long HEAD; |
889 |
private static final long TAIL; |
890 |
private static final long ITEM; |
891 |
private static final long NEXT; |
892 |
static { |
893 |
try { |
894 |
HEAD = U.objectFieldOffset |
895 |
(ConcurrentLinkedQueue.class.getDeclaredField("head")); |
896 |
TAIL = U.objectFieldOffset |
897 |
(ConcurrentLinkedQueue.class.getDeclaredField("tail")); |
898 |
ITEM = U.objectFieldOffset |
899 |
(Node.class.getDeclaredField("item")); |
900 |
NEXT = U.objectFieldOffset |
901 |
(Node.class.getDeclaredField("next")); |
902 |
} catch (ReflectiveOperationException e) { |
903 |
throw new Error(e); |
904 |
} |
905 |
} |
906 |
} |