1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* 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 |
* ConcurrentModificationException}, and may proceed concurrently with |
40 |
* 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 |
sun.misc.Unsafe.getUnsafe(); |
170 |
private static final long nextOffset = |
171 |
objectFieldOffset(UNSAFE, "next", Node.class); |
172 |
private static final long itemOffset = |
173 |
objectFieldOffset(UNSAFE, "item", Node.class); |
174 |
} |
175 |
|
176 |
/** |
177 |
* A node from which the first live (non-deleted) node (if any) |
178 |
* can be reached in O(1) time. |
179 |
* Invariants: |
180 |
* - all live nodes are reachable from head via succ() |
181 |
* - head != null |
182 |
* - (tmp = head).next != tmp || tmp != head |
183 |
* Non-invariants: |
184 |
* - head.item may or may not be null. |
185 |
* - it is permitted for tail to lag behind head, that is, for tail |
186 |
* to not be reachable from head! |
187 |
*/ |
188 |
private transient volatile Node<E> head; |
189 |
|
190 |
/** |
191 |
* A node from which the last node on list (that is, the unique |
192 |
* node with node.next == null) can be reached in O(1) time. |
193 |
* Invariants: |
194 |
* - the last node is always reachable from tail via succ() |
195 |
* - tail != null |
196 |
* Non-invariants: |
197 |
* - tail.item may or may not be null. |
198 |
* - it is permitted for tail to lag behind head, that is, for tail |
199 |
* to not be reachable from head! |
200 |
* - tail.next may or may not be self-pointing to tail. |
201 |
*/ |
202 |
private transient volatile Node<E> tail; |
203 |
|
204 |
|
205 |
/** |
206 |
* Creates a {@code ConcurrentLinkedQueue} that is initially empty. |
207 |
*/ |
208 |
public ConcurrentLinkedQueue() { |
209 |
head = tail = new Node<E>(null); |
210 |
} |
211 |
|
212 |
/** |
213 |
* Creates a {@code ConcurrentLinkedQueue} |
214 |
* initially containing the elements of the given collection, |
215 |
* added in traversal order of the collection's iterator. |
216 |
* |
217 |
* @param c the collection of elements to initially contain |
218 |
* @throws NullPointerException if the specified collection or any |
219 |
* of its elements are null |
220 |
*/ |
221 |
public ConcurrentLinkedQueue(Collection<? extends E> c) { |
222 |
Node<E> h = null, t = null; |
223 |
for (E e : c) { |
224 |
checkNotNull(e); |
225 |
Node<E> newNode = new Node<E>(e); |
226 |
if (h == null) |
227 |
h = t = newNode; |
228 |
else { |
229 |
t.lazySetNext(newNode); |
230 |
t = newNode; |
231 |
} |
232 |
} |
233 |
if (h == null) |
234 |
h = t = new Node<E>(null); |
235 |
head = h; |
236 |
tail = t; |
237 |
} |
238 |
|
239 |
// Have to override just to update the javadoc |
240 |
|
241 |
/** |
242 |
* Inserts the specified element at the tail of this queue. |
243 |
* |
244 |
* @return {@code true} (as specified by {@link Collection#add}) |
245 |
* @throws NullPointerException if the specified element is null |
246 |
*/ |
247 |
public boolean add(E e) { |
248 |
return offer(e); |
249 |
} |
250 |
|
251 |
/** |
252 |
* Try to CAS head to p. If successful, repoint old head to itself |
253 |
* as sentinel for succ(), below. |
254 |
*/ |
255 |
final void updateHead(Node<E> h, Node<E> p) { |
256 |
if (h != p && casHead(h, p)) |
257 |
h.lazySetNext(h); |
258 |
} |
259 |
|
260 |
/** |
261 |
* Returns the successor of p, or the head node if p.next has been |
262 |
* linked to self, which will only be true if traversing with a |
263 |
* stale pointer that is now off the list. |
264 |
*/ |
265 |
final Node<E> succ(Node<E> p) { |
266 |
Node<E> next = p.next; |
267 |
return (p == next) ? head : next; |
268 |
} |
269 |
|
270 |
/** |
271 |
* Inserts the specified element at the tail of this queue. |
272 |
* |
273 |
* @return {@code true} (as specified by {@link Queue#offer}) |
274 |
* @throws NullPointerException if the specified element is null |
275 |
*/ |
276 |
public boolean offer(E e) { |
277 |
checkNotNull(e); |
278 |
final Node<E> newNode = new Node<E>(e); |
279 |
|
280 |
for (Node<E> t = tail, p = t;;) { |
281 |
Node<E> q = p.next; |
282 |
if (q == null) { |
283 |
// p is last node |
284 |
if (p.casNext(null, newNode)) { |
285 |
// Successful CAS is the linearization point |
286 |
// for e to become an element of this queue, |
287 |
// and for newNode to become "live". |
288 |
if (p != t) // hop two nodes at a time |
289 |
casTail(t, newNode); // Failure is OK. |
290 |
return true; |
291 |
} |
292 |
// Lost CAS race to another thread; re-read next |
293 |
} |
294 |
else if (p == q) |
295 |
// We have fallen off list. If tail is unchanged, it |
296 |
// will also be off-list, in which case we need to |
297 |
// jump to head, from which all live nodes are always |
298 |
// reachable. Else the new tail is a better bet. |
299 |
p = (t != (t = tail)) ? t : head; |
300 |
else |
301 |
// Check for tail updates after two hops. |
302 |
p = (p != t && t != (t = tail)) ? t : q; |
303 |
} |
304 |
} |
305 |
|
306 |
public E poll() { |
307 |
restartFromHead: |
308 |
for (;;) { |
309 |
for (Node<E> h = head, p = h, q;;) { |
310 |
E item = p.item; |
311 |
|
312 |
if (item != null && p.casItem(item, null)) { |
313 |
// Successful CAS is the linearization point |
314 |
// for item to be removed from this queue. |
315 |
if (p != h) // hop two nodes at a time |
316 |
updateHead(h, ((q = p.next) != null) ? q : p); |
317 |
return item; |
318 |
} |
319 |
else if ((q = p.next) == null) { |
320 |
updateHead(h, p); |
321 |
return null; |
322 |
} |
323 |
else if (p == q) |
324 |
continue restartFromHead; |
325 |
else |
326 |
p = q; |
327 |
} |
328 |
} |
329 |
} |
330 |
|
331 |
public E peek() { |
332 |
restartFromHead: |
333 |
for (;;) { |
334 |
for (Node<E> h = head, p = h, q;;) { |
335 |
E item = p.item; |
336 |
if (item != null || (q = p.next) == null) { |
337 |
updateHead(h, p); |
338 |
return item; |
339 |
} |
340 |
else if (p == q) |
341 |
continue restartFromHead; |
342 |
else |
343 |
p = q; |
344 |
} |
345 |
} |
346 |
} |
347 |
|
348 |
/** |
349 |
* Returns the first live (non-deleted) node on list, or null if none. |
350 |
* This is yet another variant of poll/peek; here returning the |
351 |
* first node, not element. We could make peek() a wrapper around |
352 |
* first(), but that would cost an extra volatile read of item, |
353 |
* and the need to add a retry loop to deal with the possibility |
354 |
* of losing a race to a concurrent poll(). |
355 |
*/ |
356 |
Node<E> first() { |
357 |
restartFromHead: |
358 |
for (;;) { |
359 |
for (Node<E> h = head, p = h, q;;) { |
360 |
boolean hasItem = (p.item != null); |
361 |
if (hasItem || (q = p.next) == null) { |
362 |
updateHead(h, p); |
363 |
return hasItem ? p : null; |
364 |
} |
365 |
else if (p == q) |
366 |
continue restartFromHead; |
367 |
else |
368 |
p = q; |
369 |
} |
370 |
} |
371 |
} |
372 |
|
373 |
/** |
374 |
* Returns {@code true} if this queue contains no elements. |
375 |
* |
376 |
* @return {@code true} if this queue contains no elements |
377 |
*/ |
378 |
public boolean isEmpty() { |
379 |
return first() == null; |
380 |
} |
381 |
|
382 |
/** |
383 |
* Returns the number of elements in this queue. If this queue |
384 |
* contains more than {@code Integer.MAX_VALUE} elements, returns |
385 |
* {@code Integer.MAX_VALUE}. |
386 |
* |
387 |
* <p>Beware that, unlike in most collections, this method is |
388 |
* <em>NOT</em> a constant-time operation. Because of the |
389 |
* asynchronous nature of these queues, determining the current |
390 |
* number of elements requires an O(n) traversal. |
391 |
* Additionally, if elements are added or removed during execution |
392 |
* of this method, the returned result may be inaccurate. Thus, |
393 |
* this method is typically not very useful in concurrent |
394 |
* applications. |
395 |
* |
396 |
* @return the number of elements in this queue |
397 |
*/ |
398 |
public int size() { |
399 |
int count = 0; |
400 |
for (Node<E> p = first(); p != null; p = succ(p)) |
401 |
if (p.item != null) |
402 |
// Collection.size() spec says to max out |
403 |
if (++count == Integer.MAX_VALUE) |
404 |
break; |
405 |
return count; |
406 |
} |
407 |
|
408 |
/** |
409 |
* Returns {@code true} if this queue contains the specified element. |
410 |
* More formally, returns {@code true} if and only if this queue contains |
411 |
* at least one element {@code e} such that {@code o.equals(e)}. |
412 |
* |
413 |
* @param o object to be checked for containment in this queue |
414 |
* @return {@code true} if this queue contains the specified element |
415 |
*/ |
416 |
public boolean contains(Object o) { |
417 |
if (o == null) return false; |
418 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
419 |
E item = p.item; |
420 |
if (item != null && o.equals(item)) |
421 |
return true; |
422 |
} |
423 |
return false; |
424 |
} |
425 |
|
426 |
/** |
427 |
* Removes a single instance of the specified element from this queue, |
428 |
* if it is present. More formally, removes an element {@code e} such |
429 |
* that {@code o.equals(e)}, if this queue contains one or more such |
430 |
* elements. |
431 |
* Returns {@code true} if this queue contained the specified element |
432 |
* (or equivalently, if this queue changed as a result of the call). |
433 |
* |
434 |
* @param o element to be removed from this queue, if present |
435 |
* @return {@code true} if this queue changed as a result of the call |
436 |
*/ |
437 |
public boolean remove(Object o) { |
438 |
if (o == null) return false; |
439 |
Node<E> pred = null; |
440 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
441 |
E item = p.item; |
442 |
if (item != null && |
443 |
o.equals(item) && |
444 |
p.casItem(item, null)) { |
445 |
Node<E> next = succ(p); |
446 |
if (pred != null && next != null) |
447 |
pred.casNext(p, next); |
448 |
return true; |
449 |
} |
450 |
pred = p; |
451 |
} |
452 |
return false; |
453 |
} |
454 |
|
455 |
/** |
456 |
* Appends all of the elements in the specified collection to the end of |
457 |
* this queue, in the order that they are returned by the specified |
458 |
* collection's iterator. Attempts to {@code addAll} of a queue to |
459 |
* itself result in {@code IllegalArgumentException}. |
460 |
* |
461 |
* @param c the elements to be inserted into this queue |
462 |
* @return {@code true} if this queue changed as a result of the call |
463 |
* @throws NullPointerException if the specified collection or any |
464 |
* of its elements are null |
465 |
* @throws IllegalArgumentException if the collection is this queue |
466 |
*/ |
467 |
public boolean addAll(Collection<? extends E> c) { |
468 |
if (c == this) |
469 |
// As historically specified in AbstractQueue#addAll |
470 |
throw new IllegalArgumentException(); |
471 |
|
472 |
// Copy c into a private chain of Nodes |
473 |
Node<E> beginningOfTheEnd = null, last = null; |
474 |
for (E e : c) { |
475 |
checkNotNull(e); |
476 |
Node<E> newNode = new Node<E>(e); |
477 |
if (beginningOfTheEnd == null) |
478 |
beginningOfTheEnd = last = newNode; |
479 |
else { |
480 |
last.lazySetNext(newNode); |
481 |
last = newNode; |
482 |
} |
483 |
} |
484 |
if (beginningOfTheEnd == null) |
485 |
return false; |
486 |
|
487 |
// Atomically append the chain at the tail of this collection |
488 |
for (Node<E> t = tail, p = t;;) { |
489 |
Node<E> q = p.next; |
490 |
if (q == null) { |
491 |
// p is last node |
492 |
if (p.casNext(null, beginningOfTheEnd)) { |
493 |
// Successful CAS is the linearization point |
494 |
// for all elements to be added to this queue. |
495 |
if (!casTail(t, last)) { |
496 |
// Try a little harder to update tail, |
497 |
// since we may be adding many elements. |
498 |
t = tail; |
499 |
if (last.next == null) |
500 |
casTail(t, last); |
501 |
} |
502 |
return true; |
503 |
} |
504 |
// Lost CAS race to another thread; re-read next |
505 |
} |
506 |
else if (p == q) |
507 |
// We have fallen off list. If tail is unchanged, it |
508 |
// will also be off-list, in which case we need to |
509 |
// jump to head, from which all live nodes are always |
510 |
// reachable. Else the new tail is a better bet. |
511 |
p = (t != (t = tail)) ? t : head; |
512 |
else |
513 |
// Check for tail updates after two hops. |
514 |
p = (p != t && t != (t = tail)) ? t : q; |
515 |
} |
516 |
} |
517 |
|
518 |
/** |
519 |
* Returns an array containing all of the elements in this queue, in |
520 |
* proper sequence. |
521 |
* |
522 |
* <p>The returned array will be "safe" in that no references to it are |
523 |
* maintained by this queue. (In other words, this method must allocate |
524 |
* a new array). The caller is thus free to modify the returned array. |
525 |
* |
526 |
* <p>This method acts as bridge between array-based and collection-based |
527 |
* APIs. |
528 |
* |
529 |
* @return an array containing all of the elements in this queue |
530 |
*/ |
531 |
public Object[] toArray() { |
532 |
// Use ArrayList to deal with resizing. |
533 |
ArrayList<E> al = new ArrayList<E>(); |
534 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
535 |
E item = p.item; |
536 |
if (item != null) |
537 |
al.add(item); |
538 |
} |
539 |
return al.toArray(); |
540 |
} |
541 |
|
542 |
/** |
543 |
* Returns an array containing all of the elements in this queue, in |
544 |
* proper sequence; the runtime type of the returned array is that of |
545 |
* the specified array. If the queue fits in the specified array, it |
546 |
* is returned therein. Otherwise, a new array is allocated with the |
547 |
* runtime type of the specified array and the size of this queue. |
548 |
* |
549 |
* <p>If this queue fits in the specified array with room to spare |
550 |
* (i.e., the array has more elements than this queue), the element in |
551 |
* the array immediately following the end of the queue is set to |
552 |
* {@code null}. |
553 |
* |
554 |
* <p>Like the {@link #toArray()} method, this method acts as bridge between |
555 |
* array-based and collection-based APIs. Further, this method allows |
556 |
* precise control over the runtime type of the output array, and may, |
557 |
* under certain circumstances, be used to save allocation costs. |
558 |
* |
559 |
* <p>Suppose {@code x} is a queue known to contain only strings. |
560 |
* The following code can be used to dump the queue into a newly |
561 |
* allocated array of {@code String}: |
562 |
* |
563 |
* <pre> |
564 |
* String[] y = x.toArray(new String[0]);</pre> |
565 |
* |
566 |
* Note that {@code toArray(new Object[0])} is identical in function to |
567 |
* {@code toArray()}. |
568 |
* |
569 |
* @param a the array into which the elements of the queue are to |
570 |
* be stored, if it is big enough; otherwise, a new array of the |
571 |
* same runtime type is allocated for this purpose |
572 |
* @return an array containing all of the elements in this queue |
573 |
* @throws ArrayStoreException if the runtime type of the specified array |
574 |
* is not a supertype of the runtime type of every element in |
575 |
* this queue |
576 |
* @throws NullPointerException if the specified array is null |
577 |
*/ |
578 |
@SuppressWarnings("unchecked") |
579 |
public <T> T[] toArray(T[] a) { |
580 |
// try to use sent-in array |
581 |
int k = 0; |
582 |
Node<E> p; |
583 |
for (p = first(); p != null && k < a.length; p = succ(p)) { |
584 |
E item = p.item; |
585 |
if (item != null) |
586 |
a[k++] = (T)item; |
587 |
} |
588 |
if (p == null) { |
589 |
if (k < a.length) |
590 |
a[k] = null; |
591 |
return a; |
592 |
} |
593 |
|
594 |
// If won't fit, use ArrayList version |
595 |
ArrayList<E> al = new ArrayList<E>(); |
596 |
for (Node<E> q = first(); q != null; q = succ(q)) { |
597 |
E item = q.item; |
598 |
if (item != null) |
599 |
al.add(item); |
600 |
} |
601 |
return al.toArray(a); |
602 |
} |
603 |
|
604 |
/** |
605 |
* Returns an iterator over the elements in this queue in proper sequence. |
606 |
* The elements will be returned in order from first (head) to last (tail). |
607 |
* |
608 |
* <p>The returned {@code Iterator} is a "weakly consistent" iterator that |
609 |
* will never throw {@link java.util.ConcurrentModificationException |
610 |
* ConcurrentModificationException}, |
611 |
* and guarantees to traverse elements as they existed upon |
612 |
* construction of the iterator, and may (but is not guaranteed to) |
613 |
* reflect any modifications subsequent to construction. |
614 |
* |
615 |
* @return an iterator over the elements in this queue in proper sequence |
616 |
*/ |
617 |
public Iterator<E> iterator() { |
618 |
return new Itr(); |
619 |
} |
620 |
|
621 |
private class Itr implements Iterator<E> { |
622 |
/** |
623 |
* Next node to return item for. |
624 |
*/ |
625 |
private Node<E> nextNode; |
626 |
|
627 |
/** |
628 |
* nextItem holds on to item fields because once we claim |
629 |
* that an element exists in hasNext(), we must return it in |
630 |
* the following next() call even if it was in the process of |
631 |
* being removed when hasNext() was called. |
632 |
*/ |
633 |
private E nextItem; |
634 |
|
635 |
/** |
636 |
* Node of the last returned item, to support remove. |
637 |
*/ |
638 |
private Node<E> lastRet; |
639 |
|
640 |
Itr() { |
641 |
advance(); |
642 |
} |
643 |
|
644 |
/** |
645 |
* Moves to next valid node and returns item to return for |
646 |
* next(), or null if no such. |
647 |
*/ |
648 |
private E advance() { |
649 |
lastRet = nextNode; |
650 |
E x = nextItem; |
651 |
|
652 |
Node<E> pred, p; |
653 |
if (nextNode == null) { |
654 |
p = first(); |
655 |
pred = null; |
656 |
} else { |
657 |
pred = nextNode; |
658 |
p = succ(nextNode); |
659 |
} |
660 |
|
661 |
for (;;) { |
662 |
if (p == null) { |
663 |
nextNode = null; |
664 |
nextItem = null; |
665 |
return x; |
666 |
} |
667 |
E item = p.item; |
668 |
if (item != null) { |
669 |
nextNode = p; |
670 |
nextItem = item; |
671 |
return x; |
672 |
} else { |
673 |
// skip over nulls |
674 |
Node<E> next = succ(p); |
675 |
if (pred != null && next != null) |
676 |
pred.casNext(p, next); |
677 |
p = next; |
678 |
} |
679 |
} |
680 |
} |
681 |
|
682 |
public boolean hasNext() { |
683 |
return nextNode != null; |
684 |
} |
685 |
|
686 |
public E next() { |
687 |
if (nextNode == null) throw new NoSuchElementException(); |
688 |
return advance(); |
689 |
} |
690 |
|
691 |
public void remove() { |
692 |
Node<E> l = lastRet; |
693 |
if (l == null) throw new IllegalStateException(); |
694 |
// rely on a future traversal to relink. |
695 |
l.item = null; |
696 |
lastRet = null; |
697 |
} |
698 |
} |
699 |
|
700 |
/** |
701 |
* Saves the state to a stream (that is, serializes it). |
702 |
* |
703 |
* @serialData All of the elements (each an {@code E}) in |
704 |
* the proper order, followed by a null |
705 |
* @param s the stream |
706 |
*/ |
707 |
private void writeObject(java.io.ObjectOutputStream s) |
708 |
throws java.io.IOException { |
709 |
|
710 |
// Write out any hidden stuff |
711 |
s.defaultWriteObject(); |
712 |
|
713 |
// Write out all elements in the proper order. |
714 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
715 |
Object item = p.item; |
716 |
if (item != null) |
717 |
s.writeObject(item); |
718 |
} |
719 |
|
720 |
// Use trailing null as sentinel |
721 |
s.writeObject(null); |
722 |
} |
723 |
|
724 |
/** |
725 |
* Reconstitutes the instance from a stream (that is, deserializes it). |
726 |
* @param s the stream |
727 |
*/ |
728 |
private void readObject(java.io.ObjectInputStream s) |
729 |
throws java.io.IOException, ClassNotFoundException { |
730 |
s.defaultReadObject(); |
731 |
|
732 |
// Read in elements until trailing null sentinel found |
733 |
Node<E> h = null, t = null; |
734 |
Object item; |
735 |
while ((item = s.readObject()) != null) { |
736 |
@SuppressWarnings("unchecked") |
737 |
Node<E> newNode = new Node<E>((E) item); |
738 |
if (h == null) |
739 |
h = t = newNode; |
740 |
else { |
741 |
t.lazySetNext(newNode); |
742 |
t = newNode; |
743 |
} |
744 |
} |
745 |
if (h == null) |
746 |
h = t = new Node<E>(null); |
747 |
head = h; |
748 |
tail = t; |
749 |
} |
750 |
|
751 |
/** |
752 |
* Throws NullPointerException if argument is null. |
753 |
* |
754 |
* @param v the element |
755 |
*/ |
756 |
private static void checkNotNull(Object v) { |
757 |
if (v == null) |
758 |
throw new NullPointerException(); |
759 |
} |
760 |
|
761 |
// Unsafe mechanics |
762 |
|
763 |
private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe(); |
764 |
private static final long headOffset = |
765 |
objectFieldOffset(UNSAFE, "head", ConcurrentLinkedQueue.class); |
766 |
private static final long tailOffset = |
767 |
objectFieldOffset(UNSAFE, "tail", ConcurrentLinkedQueue.class); |
768 |
|
769 |
private boolean casTail(Node<E> cmp, Node<E> val) { |
770 |
return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val); |
771 |
} |
772 |
|
773 |
private boolean casHead(Node<E> cmp, Node<E> val) { |
774 |
return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val); |
775 |
} |
776 |
|
777 |
static long objectFieldOffset(sun.misc.Unsafe UNSAFE, |
778 |
String field, Class<?> klazz) { |
779 |
try { |
780 |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field)); |
781 |
} catch (NoSuchFieldException e) { |
782 |
// Convert Exception to corresponding Error |
783 |
NoSuchFieldError error = new NoSuchFieldError(field); |
784 |
error.initCause(e); |
785 |
throw error; |
786 |
} |
787 |
} |
788 |
} |