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