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