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