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