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