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.AbstractCollection; |
10 |
import java.util.Arrays; |
11 |
import java.util.Collection; |
12 |
import java.util.Deque; |
13 |
import java.util.Iterator; |
14 |
import java.util.NoSuchElementException; |
15 |
import java.util.Objects; |
16 |
import java.util.Queue; |
17 |
import java.util.Spliterator; |
18 |
import java.util.Spliterators; |
19 |
import java.util.function.Consumer; |
20 |
|
21 |
/** |
22 |
* An unbounded concurrent {@linkplain Deque deque} based on linked nodes. |
23 |
* Concurrent insertion, removal, and access operations execute safely |
24 |
* across multiple threads. |
25 |
* A {@code ConcurrentLinkedDeque} 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>Iterators and spliterators are |
31 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
32 |
* |
33 |
* <p>Beware that, unlike in most collections, the {@code size} method |
34 |
* is <em>NOT</em> a constant-time operation. Because of the |
35 |
* asynchronous nature of these deques, determining the current number |
36 |
* of elements requires a traversal of the elements, and so may report |
37 |
* inaccurate results if this collection is modified during traversal. |
38 |
* Additionally, the bulk operations {@code addAll}, |
39 |
* {@code removeAll}, {@code retainAll}, {@code containsAll}, |
40 |
* {@code equals}, and {@code toArray} are <em>not</em> guaranteed |
41 |
* to be performed atomically. For example, an iterator operating |
42 |
* concurrently with an {@code addAll} operation might view only some |
43 |
* of the added elements. |
44 |
* |
45 |
* <p>This class and its iterator implement all of the <em>optional</em> |
46 |
* methods of the {@link Deque} and {@link Iterator} interfaces. |
47 |
* |
48 |
* <p>Memory consistency effects: As with other concurrent collections, |
49 |
* actions in a thread prior to placing an object into a |
50 |
* {@code ConcurrentLinkedDeque} |
51 |
* <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> |
52 |
* actions subsequent to the access or removal of that element from |
53 |
* the {@code ConcurrentLinkedDeque} in another thread. |
54 |
* |
55 |
* <p>This class is a member of the |
56 |
* <a href="{@docRoot}/../technotes/guides/collections/index.html"> |
57 |
* Java Collections Framework</a>. |
58 |
* |
59 |
* @since 1.7 |
60 |
* @author Doug Lea |
61 |
* @author Martin Buchholz |
62 |
* @param <E> the type of elements held in this deque |
63 |
*/ |
64 |
public class ConcurrentLinkedDeque<E> |
65 |
extends AbstractCollection<E> |
66 |
implements Deque<E>, java.io.Serializable { |
67 |
|
68 |
/* |
69 |
* This is an implementation of a concurrent lock-free deque |
70 |
* supporting interior removes but not interior insertions, as |
71 |
* required to support the entire Deque interface. |
72 |
* |
73 |
* We extend the techniques developed for ConcurrentLinkedQueue and |
74 |
* LinkedTransferQueue (see the internal docs for those classes). |
75 |
* Understanding the ConcurrentLinkedQueue implementation is a |
76 |
* prerequisite for understanding the implementation of this class. |
77 |
* |
78 |
* The data structure is a symmetrical doubly-linked "GC-robust" |
79 |
* linked list of nodes. We minimize the number of volatile writes |
80 |
* using two techniques: advancing multiple hops with a single CAS |
81 |
* and mixing volatile and non-volatile writes of the same memory |
82 |
* locations. |
83 |
* |
84 |
* A node contains the expected E ("item") and links to predecessor |
85 |
* ("prev") and successor ("next") nodes: |
86 |
* |
87 |
* class Node<E> { volatile Node<E> prev, next; volatile E item; } |
88 |
* |
89 |
* A node p is considered "live" if it contains a non-null item |
90 |
* (p.item != null). When an item is CASed to null, the item is |
91 |
* atomically logically deleted from the collection. |
92 |
* |
93 |
* At any time, there is precisely one "first" node with a null |
94 |
* prev reference that terminates any chain of prev references |
95 |
* starting at a live node. Similarly there is precisely one |
96 |
* "last" node terminating any chain of next references starting at |
97 |
* a live node. The "first" and "last" nodes may or may not be live. |
98 |
* The "first" and "last" nodes are always mutually reachable. |
99 |
* |
100 |
* A new element is added atomically by CASing the null prev or |
101 |
* next reference in the first or last node to a fresh node |
102 |
* containing the element. The element's node atomically becomes |
103 |
* "live" at that point. |
104 |
* |
105 |
* A node is considered "active" if it is a live node, or the |
106 |
* first or last node. Active nodes cannot be unlinked. |
107 |
* |
108 |
* A "self-link" is a next or prev reference that is the same node: |
109 |
* p.prev == p or p.next == p |
110 |
* Self-links are used in the node unlinking process. Active nodes |
111 |
* never have self-links. |
112 |
* |
113 |
* A node p is active if and only if: |
114 |
* |
115 |
* p.item != null || |
116 |
* (p.prev == null && p.next != p) || |
117 |
* (p.next == null && p.prev != p) |
118 |
* |
119 |
* The deque object has two node references, "head" and "tail". |
120 |
* The head and tail are only approximations to the first and last |
121 |
* nodes of the deque. The first node can always be found by |
122 |
* following prev pointers from head; likewise for tail. However, |
123 |
* it is permissible for head and tail to be referring to deleted |
124 |
* nodes that have been unlinked and so may not be reachable from |
125 |
* any live node. |
126 |
* |
127 |
* There are 3 stages of node deletion; |
128 |
* "logical deletion", "unlinking", and "gc-unlinking". |
129 |
* |
130 |
* 1. "logical deletion" by CASing item to null atomically removes |
131 |
* the element from the collection, and makes the containing node |
132 |
* eligible for unlinking. |
133 |
* |
134 |
* 2. "unlinking" makes a deleted node unreachable from active |
135 |
* nodes, and thus eventually reclaimable by GC. Unlinked nodes |
136 |
* may remain reachable indefinitely from an iterator. |
137 |
* |
138 |
* Physical node unlinking is merely an optimization (albeit a |
139 |
* critical one), and so can be performed at our convenience. At |
140 |
* any time, the set of live nodes maintained by prev and next |
141 |
* links are identical, that is, the live nodes found via next |
142 |
* links from the first node is equal to the elements found via |
143 |
* prev links from the last node. However, this is not true for |
144 |
* nodes that have already been logically deleted - such nodes may |
145 |
* be reachable in one direction only. |
146 |
* |
147 |
* 3. "gc-unlinking" takes unlinking further by making active |
148 |
* nodes unreachable from deleted nodes, making it easier for the |
149 |
* GC to reclaim future deleted nodes. This step makes the data |
150 |
* structure "gc-robust", as first described in detail by Boehm |
151 |
* (http://portal.acm.org/citation.cfm?doid=503272.503282). |
152 |
* |
153 |
* GC-unlinked nodes may remain reachable indefinitely from an |
154 |
* iterator, but unlike unlinked nodes, are never reachable from |
155 |
* head or tail. |
156 |
* |
157 |
* Making the data structure GC-robust will eliminate the risk of |
158 |
* unbounded memory retention with conservative GCs and is likely |
159 |
* to improve performance with generational GCs. |
160 |
* |
161 |
* When a node is dequeued at either end, e.g. via poll(), we would |
162 |
* like to break any references from the node to active nodes. We |
163 |
* develop further the use of self-links that was very effective in |
164 |
* other concurrent collection classes. The idea is to replace |
165 |
* prev and next pointers with special values that are interpreted |
166 |
* to mean off-the-list-at-one-end. These are approximations, but |
167 |
* good enough to preserve the properties we want in our |
168 |
* traversals, e.g. we guarantee that a traversal will never visit |
169 |
* the same element twice, but we don't guarantee whether a |
170 |
* traversal that runs out of elements will be able to see more |
171 |
* elements later after enqueues at that end. Doing gc-unlinking |
172 |
* safely is particularly tricky, since any node can be in use |
173 |
* indefinitely (for example by an iterator). We must ensure that |
174 |
* the nodes pointed at by head/tail never get gc-unlinked, since |
175 |
* head/tail are needed to get "back on track" by other nodes that |
176 |
* are gc-unlinked. gc-unlinking accounts for much of the |
177 |
* implementation complexity. |
178 |
* |
179 |
* Since neither unlinking nor gc-unlinking are necessary for |
180 |
* correctness, there are many implementation choices regarding |
181 |
* frequency (eagerness) of these operations. Since volatile |
182 |
* reads are likely to be much cheaper than CASes, saving CASes by |
183 |
* unlinking multiple adjacent nodes at a time may be a win. |
184 |
* gc-unlinking can be performed rarely and still be effective, |
185 |
* since it is most important that long chains of deleted nodes |
186 |
* are occasionally broken. |
187 |
* |
188 |
* The actual representation we use is that p.next == p means to |
189 |
* goto the first node (which in turn is reached by following prev |
190 |
* pointers from head), and p.next == null && p.prev == p means |
191 |
* that the iteration is at an end and that p is a (static final) |
192 |
* dummy node, NEXT_TERMINATOR, and not the last active node. |
193 |
* Finishing the iteration when encountering such a TERMINATOR is |
194 |
* good enough for read-only traversals, so such traversals can use |
195 |
* p.next == null as the termination condition. When we need to |
196 |
* find the last (active) node, for enqueueing a new node, we need |
197 |
* to check whether we have reached a TERMINATOR node; if so, |
198 |
* restart traversal from tail. |
199 |
* |
200 |
* The implementation is completely directionally symmetrical, |
201 |
* except that most public methods that iterate through the list |
202 |
* follow next pointers ("forward" direction). |
203 |
* |
204 |
* We believe (without full proof) that all single-element deque |
205 |
* operations (e.g., addFirst, peekLast, pollLast) are linearizable |
206 |
* (see Herlihy and Shavit's book). However, some combinations of |
207 |
* operations are known not to be linearizable. In particular, |
208 |
* when an addFirst(A) is racing with pollFirst() removing B, it is |
209 |
* possible for an observer iterating over the elements to observe |
210 |
* A B C and subsequently observe A C, even though no interior |
211 |
* removes are ever performed. Nevertheless, iterators behave |
212 |
* reasonably, providing the "weakly consistent" guarantees. |
213 |
* |
214 |
* Empirically, microbenchmarks suggest that this class adds about |
215 |
* 40% overhead relative to ConcurrentLinkedQueue, which feels as |
216 |
* good as we can hope for. |
217 |
*/ |
218 |
|
219 |
private static final long serialVersionUID = 876323262645176354L; |
220 |
|
221 |
/** |
222 |
* A node from which the first node on list (that is, the unique node p |
223 |
* with p.prev == null && p.next != p) can be reached in O(1) time. |
224 |
* Invariants: |
225 |
* - the first node is always O(1) reachable from head via prev links |
226 |
* - all live nodes are reachable from the first node via succ() |
227 |
* - head != null |
228 |
* - (tmp = head).next != tmp || tmp != head |
229 |
* - head is never gc-unlinked (but may be unlinked) |
230 |
* Non-invariants: |
231 |
* - head.item may or may not be null |
232 |
* - head may not be reachable from the first or last node, or from tail |
233 |
*/ |
234 |
private transient volatile Node<E> head; |
235 |
|
236 |
/** |
237 |
* A node from which the last node on list (that is, the unique node p |
238 |
* with p.next == null && p.prev != p) can be reached in O(1) time. |
239 |
* Invariants: |
240 |
* - the last node is always O(1) reachable from tail via next links |
241 |
* - all live nodes are reachable from the last node via pred() |
242 |
* - tail != null |
243 |
* - tail is never gc-unlinked (but may be unlinked) |
244 |
* Non-invariants: |
245 |
* - tail.item may or may not be null |
246 |
* - tail may not be reachable from the first or last node, or from head |
247 |
*/ |
248 |
private transient volatile Node<E> tail; |
249 |
|
250 |
private static final Node<Object> PREV_TERMINATOR, NEXT_TERMINATOR; |
251 |
|
252 |
@SuppressWarnings("unchecked") |
253 |
Node<E> prevTerminator() { |
254 |
return (Node<E>) PREV_TERMINATOR; |
255 |
} |
256 |
|
257 |
@SuppressWarnings("unchecked") |
258 |
Node<E> nextTerminator() { |
259 |
return (Node<E>) NEXT_TERMINATOR; |
260 |
} |
261 |
|
262 |
static final class Node<E> { |
263 |
volatile Node<E> prev; |
264 |
volatile E item; |
265 |
volatile Node<E> next; |
266 |
|
267 |
Node() { // default constructor for NEXT_TERMINATOR, PREV_TERMINATOR |
268 |
} |
269 |
|
270 |
/** |
271 |
* Constructs a new node. Uses relaxed write because item can |
272 |
* only be seen after publication via casNext or casPrev. |
273 |
*/ |
274 |
Node(E item) { |
275 |
U.putObject(this, ITEM, item); |
276 |
} |
277 |
|
278 |
boolean casItem(E cmp, E val) { |
279 |
return U.compareAndSwapObject(this, ITEM, cmp, val); |
280 |
} |
281 |
|
282 |
void lazySetNext(Node<E> val) { |
283 |
U.putOrderedObject(this, NEXT, val); |
284 |
} |
285 |
|
286 |
boolean casNext(Node<E> cmp, Node<E> val) { |
287 |
return U.compareAndSwapObject(this, NEXT, cmp, val); |
288 |
} |
289 |
|
290 |
void lazySetPrev(Node<E> val) { |
291 |
U.putOrderedObject(this, PREV, val); |
292 |
} |
293 |
|
294 |
boolean casPrev(Node<E> cmp, Node<E> val) { |
295 |
return U.compareAndSwapObject(this, PREV, cmp, val); |
296 |
} |
297 |
|
298 |
// Unsafe mechanics |
299 |
|
300 |
private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe(); |
301 |
private static final long PREV; |
302 |
private static final long ITEM; |
303 |
private static final long NEXT; |
304 |
|
305 |
static { |
306 |
try { |
307 |
PREV = U.objectFieldOffset |
308 |
(Node.class.getDeclaredField("prev")); |
309 |
ITEM = U.objectFieldOffset |
310 |
(Node.class.getDeclaredField("item")); |
311 |
NEXT = U.objectFieldOffset |
312 |
(Node.class.getDeclaredField("next")); |
313 |
} catch (ReflectiveOperationException e) { |
314 |
throw new Error(e); |
315 |
} |
316 |
} |
317 |
} |
318 |
|
319 |
/** |
320 |
* Links e as first element. |
321 |
*/ |
322 |
private void linkFirst(E e) { |
323 |
final Node<E> newNode = new Node<E>(Objects.requireNonNull(e)); |
324 |
|
325 |
restartFromHead: |
326 |
for (;;) |
327 |
for (Node<E> h = head, p = h, q;;) { |
328 |
if ((q = p.prev) != null && |
329 |
(q = (p = q).prev) != null) |
330 |
// Check for head updates every other hop. |
331 |
// If p == q, we are sure to follow head instead. |
332 |
p = (h != (h = head)) ? h : q; |
333 |
else if (p.next == p) // PREV_TERMINATOR |
334 |
continue restartFromHead; |
335 |
else { |
336 |
// p is first node |
337 |
newNode.lazySetNext(p); // CAS piggyback |
338 |
if (p.casPrev(null, newNode)) { |
339 |
// Successful CAS is the linearization point |
340 |
// for e to become an element of this deque, |
341 |
// and for newNode to become "live". |
342 |
if (p != h) // hop two nodes at a time |
343 |
casHead(h, newNode); // Failure is OK. |
344 |
return; |
345 |
} |
346 |
// Lost CAS race to another thread; re-read prev |
347 |
} |
348 |
} |
349 |
} |
350 |
|
351 |
/** |
352 |
* Links e as last element. |
353 |
*/ |
354 |
private void linkLast(E e) { |
355 |
final Node<E> newNode = new Node<E>(Objects.requireNonNull(e)); |
356 |
|
357 |
restartFromTail: |
358 |
for (;;) |
359 |
for (Node<E> t = tail, p = t, q;;) { |
360 |
if ((q = p.next) != null && |
361 |
(q = (p = q).next) != null) |
362 |
// Check for tail updates every other hop. |
363 |
// If p == q, we are sure to follow tail instead. |
364 |
p = (t != (t = tail)) ? t : q; |
365 |
else if (p.prev == p) // NEXT_TERMINATOR |
366 |
continue restartFromTail; |
367 |
else { |
368 |
// p is last node |
369 |
newNode.lazySetPrev(p); // CAS piggyback |
370 |
if (p.casNext(null, newNode)) { |
371 |
// Successful CAS is the linearization point |
372 |
// for e to become an element of this deque, |
373 |
// and for newNode to become "live". |
374 |
if (p != t) // hop two nodes at a time |
375 |
casTail(t, newNode); // Failure is OK. |
376 |
return; |
377 |
} |
378 |
// Lost CAS race to another thread; re-read next |
379 |
} |
380 |
} |
381 |
} |
382 |
|
383 |
private static final int HOPS = 2; |
384 |
|
385 |
/** |
386 |
* Unlinks non-null node x. |
387 |
*/ |
388 |
void unlink(Node<E> x) { |
389 |
// assert x != null; |
390 |
// assert x.item == null; |
391 |
// assert x != PREV_TERMINATOR; |
392 |
// assert x != NEXT_TERMINATOR; |
393 |
|
394 |
final Node<E> prev = x.prev; |
395 |
final Node<E> next = x.next; |
396 |
if (prev == null) { |
397 |
unlinkFirst(x, next); |
398 |
} else if (next == null) { |
399 |
unlinkLast(x, prev); |
400 |
} else { |
401 |
// Unlink interior node. |
402 |
// |
403 |
// This is the common case, since a series of polls at the |
404 |
// same end will be "interior" removes, except perhaps for |
405 |
// the first one, since end nodes cannot be unlinked. |
406 |
// |
407 |
// At any time, all active nodes are mutually reachable by |
408 |
// following a sequence of either next or prev pointers. |
409 |
// |
410 |
// Our strategy is to find the unique active predecessor |
411 |
// and successor of x. Try to fix up their links so that |
412 |
// they point to each other, leaving x unreachable from |
413 |
// active nodes. If successful, and if x has no live |
414 |
// predecessor/successor, we additionally try to gc-unlink, |
415 |
// leaving active nodes unreachable from x, by rechecking |
416 |
// that the status of predecessor and successor are |
417 |
// unchanged and ensuring that x is not reachable from |
418 |
// tail/head, before setting x's prev/next links to their |
419 |
// logical approximate replacements, self/TERMINATOR. |
420 |
Node<E> activePred, activeSucc; |
421 |
boolean isFirst, isLast; |
422 |
int hops = 1; |
423 |
|
424 |
// Find active predecessor |
425 |
for (Node<E> p = prev; ; ++hops) { |
426 |
if (p.item != null) { |
427 |
activePred = p; |
428 |
isFirst = false; |
429 |
break; |
430 |
} |
431 |
Node<E> q = p.prev; |
432 |
if (q == null) { |
433 |
if (p.next == p) |
434 |
return; |
435 |
activePred = p; |
436 |
isFirst = true; |
437 |
break; |
438 |
} |
439 |
else if (p == q) |
440 |
return; |
441 |
else |
442 |
p = q; |
443 |
} |
444 |
|
445 |
// Find active successor |
446 |
for (Node<E> p = next; ; ++hops) { |
447 |
if (p.item != null) { |
448 |
activeSucc = p; |
449 |
isLast = false; |
450 |
break; |
451 |
} |
452 |
Node<E> q = p.next; |
453 |
if (q == null) { |
454 |
if (p.prev == p) |
455 |
return; |
456 |
activeSucc = p; |
457 |
isLast = true; |
458 |
break; |
459 |
} |
460 |
else if (p == q) |
461 |
return; |
462 |
else |
463 |
p = q; |
464 |
} |
465 |
|
466 |
// TODO: better HOP heuristics |
467 |
if (hops < HOPS |
468 |
// always squeeze out interior deleted nodes |
469 |
&& (isFirst | isLast)) |
470 |
return; |
471 |
|
472 |
// Squeeze out deleted nodes between activePred and |
473 |
// activeSucc, including x. |
474 |
skipDeletedSuccessors(activePred); |
475 |
skipDeletedPredecessors(activeSucc); |
476 |
|
477 |
// Try to gc-unlink, if possible |
478 |
if ((isFirst | isLast) && |
479 |
|
480 |
// Recheck expected state of predecessor and successor |
481 |
(activePred.next == activeSucc) && |
482 |
(activeSucc.prev == activePred) && |
483 |
(isFirst ? activePred.prev == null : activePred.item != null) && |
484 |
(isLast ? activeSucc.next == null : activeSucc.item != null)) { |
485 |
|
486 |
updateHead(); // Ensure x is not reachable from head |
487 |
updateTail(); // Ensure x is not reachable from tail |
488 |
|
489 |
// Finally, actually gc-unlink |
490 |
x.lazySetPrev(isFirst ? prevTerminator() : x); |
491 |
x.lazySetNext(isLast ? nextTerminator() : x); |
492 |
} |
493 |
} |
494 |
} |
495 |
|
496 |
/** |
497 |
* Unlinks non-null first node. |
498 |
*/ |
499 |
private void unlinkFirst(Node<E> first, Node<E> next) { |
500 |
// assert first != null; |
501 |
// assert next != null; |
502 |
// assert first.item == null; |
503 |
for (Node<E> o = null, p = next, q;;) { |
504 |
if (p.item != null || (q = p.next) == null) { |
505 |
if (o != null && p.prev != p && first.casNext(next, p)) { |
506 |
skipDeletedPredecessors(p); |
507 |
if (first.prev == null && |
508 |
(p.next == null || p.item != null) && |
509 |
p.prev == first) { |
510 |
|
511 |
updateHead(); // Ensure o is not reachable from head |
512 |
updateTail(); // Ensure o is not reachable from tail |
513 |
|
514 |
// Finally, actually gc-unlink |
515 |
o.lazySetNext(o); |
516 |
o.lazySetPrev(prevTerminator()); |
517 |
} |
518 |
} |
519 |
return; |
520 |
} |
521 |
else if (p == q) |
522 |
return; |
523 |
else { |
524 |
o = p; |
525 |
p = q; |
526 |
} |
527 |
} |
528 |
} |
529 |
|
530 |
/** |
531 |
* Unlinks non-null last node. |
532 |
*/ |
533 |
private void unlinkLast(Node<E> last, Node<E> prev) { |
534 |
// assert last != null; |
535 |
// assert prev != null; |
536 |
// assert last.item == null; |
537 |
for (Node<E> o = null, p = prev, q;;) { |
538 |
if (p.item != null || (q = p.prev) == null) { |
539 |
if (o != null && p.next != p && last.casPrev(prev, p)) { |
540 |
skipDeletedSuccessors(p); |
541 |
if (last.next == null && |
542 |
(p.prev == null || p.item != null) && |
543 |
p.next == last) { |
544 |
|
545 |
updateHead(); // Ensure o is not reachable from head |
546 |
updateTail(); // Ensure o is not reachable from tail |
547 |
|
548 |
// Finally, actually gc-unlink |
549 |
o.lazySetPrev(o); |
550 |
o.lazySetNext(nextTerminator()); |
551 |
} |
552 |
} |
553 |
return; |
554 |
} |
555 |
else if (p == q) |
556 |
return; |
557 |
else { |
558 |
o = p; |
559 |
p = q; |
560 |
} |
561 |
} |
562 |
} |
563 |
|
564 |
/** |
565 |
* Guarantees that any node which was unlinked before a call to |
566 |
* this method will be unreachable from head after it returns. |
567 |
* Does not guarantee to eliminate slack, only that head will |
568 |
* point to a node that was active while this method was running. |
569 |
*/ |
570 |
private final void updateHead() { |
571 |
// Either head already points to an active node, or we keep |
572 |
// trying to cas it to the first node until it does. |
573 |
Node<E> h, p, q; |
574 |
restartFromHead: |
575 |
while ((h = head).item == null && (p = h.prev) != null) { |
576 |
for (;;) { |
577 |
if ((q = p.prev) == null || |
578 |
(q = (p = q).prev) == null) { |
579 |
// It is possible that p is PREV_TERMINATOR, |
580 |
// but if so, the CAS is guaranteed to fail. |
581 |
if (casHead(h, p)) |
582 |
return; |
583 |
else |
584 |
continue restartFromHead; |
585 |
} |
586 |
else if (h != head) |
587 |
continue restartFromHead; |
588 |
else |
589 |
p = q; |
590 |
} |
591 |
} |
592 |
} |
593 |
|
594 |
/** |
595 |
* Guarantees that any node which was unlinked before a call to |
596 |
* this method will be unreachable from tail after it returns. |
597 |
* Does not guarantee to eliminate slack, only that tail will |
598 |
* point to a node that was active while this method was running. |
599 |
*/ |
600 |
private final void updateTail() { |
601 |
// Either tail already points to an active node, or we keep |
602 |
// trying to cas it to the last node until it does. |
603 |
Node<E> t, p, q; |
604 |
restartFromTail: |
605 |
while ((t = tail).item == null && (p = t.next) != null) { |
606 |
for (;;) { |
607 |
if ((q = p.next) == null || |
608 |
(q = (p = q).next) == null) { |
609 |
// It is possible that p is NEXT_TERMINATOR, |
610 |
// but if so, the CAS is guaranteed to fail. |
611 |
if (casTail(t, p)) |
612 |
return; |
613 |
else |
614 |
continue restartFromTail; |
615 |
} |
616 |
else if (t != tail) |
617 |
continue restartFromTail; |
618 |
else |
619 |
p = q; |
620 |
} |
621 |
} |
622 |
} |
623 |
|
624 |
private void skipDeletedPredecessors(Node<E> x) { |
625 |
whileActive: |
626 |
do { |
627 |
Node<E> prev = x.prev; |
628 |
// assert prev != null; |
629 |
// assert x != NEXT_TERMINATOR; |
630 |
// assert x != PREV_TERMINATOR; |
631 |
Node<E> p = prev; |
632 |
findActive: |
633 |
for (;;) { |
634 |
if (p.item != null) |
635 |
break findActive; |
636 |
Node<E> q = p.prev; |
637 |
if (q == null) { |
638 |
if (p.next == p) |
639 |
continue whileActive; |
640 |
break findActive; |
641 |
} |
642 |
else if (p == q) |
643 |
continue whileActive; |
644 |
else |
645 |
p = q; |
646 |
} |
647 |
|
648 |
// found active CAS target |
649 |
if (prev == p || x.casPrev(prev, p)) |
650 |
return; |
651 |
|
652 |
} while (x.item != null || x.next == null); |
653 |
} |
654 |
|
655 |
private void skipDeletedSuccessors(Node<E> x) { |
656 |
whileActive: |
657 |
do { |
658 |
Node<E> next = x.next; |
659 |
// assert next != null; |
660 |
// assert x != NEXT_TERMINATOR; |
661 |
// assert x != PREV_TERMINATOR; |
662 |
Node<E> p = next; |
663 |
findActive: |
664 |
for (;;) { |
665 |
if (p.item != null) |
666 |
break findActive; |
667 |
Node<E> q = p.next; |
668 |
if (q == null) { |
669 |
if (p.prev == p) |
670 |
continue whileActive; |
671 |
break findActive; |
672 |
} |
673 |
else if (p == q) |
674 |
continue whileActive; |
675 |
else |
676 |
p = q; |
677 |
} |
678 |
|
679 |
// found active CAS target |
680 |
if (next == p || x.casNext(next, p)) |
681 |
return; |
682 |
|
683 |
} while (x.item != null || x.prev == null); |
684 |
} |
685 |
|
686 |
/** |
687 |
* Returns the successor of p, or the first node if p.next has been |
688 |
* linked to self, which will only be true if traversing with a |
689 |
* stale pointer that is now off the list. |
690 |
*/ |
691 |
final Node<E> succ(Node<E> p) { |
692 |
// TODO: should we skip deleted nodes here? |
693 |
Node<E> q = p.next; |
694 |
return (p == q) ? first() : q; |
695 |
} |
696 |
|
697 |
/** |
698 |
* Returns the predecessor of p, or the last node if p.prev has been |
699 |
* linked to self, which will only be true if traversing with a |
700 |
* stale pointer that is now off the list. |
701 |
*/ |
702 |
final Node<E> pred(Node<E> p) { |
703 |
if (p == (p = p.prev)) |
704 |
p = last(); |
705 |
return p; |
706 |
} |
707 |
|
708 |
/** |
709 |
* Returns the first node, the unique node p for which: |
710 |
* p.prev == null && p.next != p |
711 |
* The returned node may or may not be logically deleted. |
712 |
* Guarantees that head is set to the returned node. |
713 |
*/ |
714 |
Node<E> first() { |
715 |
restartFromHead: |
716 |
for (;;) |
717 |
for (Node<E> h = head, p = h, q;;) { |
718 |
if ((q = p.prev) != null && |
719 |
(q = (p = q).prev) != null) |
720 |
// Check for head updates every other hop. |
721 |
// If p == q, we are sure to follow head instead. |
722 |
p = (h != (h = head)) ? h : q; |
723 |
else if (p == h |
724 |
// It is possible that p is PREV_TERMINATOR, |
725 |
// but if so, the CAS is guaranteed to fail. |
726 |
|| casHead(h, p)) |
727 |
return p; |
728 |
else |
729 |
continue restartFromHead; |
730 |
} |
731 |
} |
732 |
|
733 |
/** |
734 |
* Returns the last node, the unique node p for which: |
735 |
* p.next == null && p.prev != p |
736 |
* The returned node may or may not be logically deleted. |
737 |
* Guarantees that tail is set to the returned node. |
738 |
*/ |
739 |
Node<E> last() { |
740 |
restartFromTail: |
741 |
for (;;) |
742 |
for (Node<E> t = tail, p = t, q;;) { |
743 |
if ((q = p.next) != null && |
744 |
(q = (p = q).next) != null) |
745 |
// Check for tail updates every other hop. |
746 |
// If p == q, we are sure to follow tail instead. |
747 |
p = (t != (t = tail)) ? t : q; |
748 |
else if (p == t |
749 |
// It is possible that p is NEXT_TERMINATOR, |
750 |
// but if so, the CAS is guaranteed to fail. |
751 |
|| casTail(t, p)) |
752 |
return p; |
753 |
else |
754 |
continue restartFromTail; |
755 |
} |
756 |
} |
757 |
|
758 |
// Minor convenience utilities |
759 |
|
760 |
/** |
761 |
* Returns element unless it is null, in which case throws |
762 |
* NoSuchElementException. |
763 |
* |
764 |
* @param v the element |
765 |
* @return the element |
766 |
*/ |
767 |
private E screenNullResult(E v) { |
768 |
if (v == null) |
769 |
throw new NoSuchElementException(); |
770 |
return v; |
771 |
} |
772 |
|
773 |
/** |
774 |
* Constructs an empty deque. |
775 |
*/ |
776 |
public ConcurrentLinkedDeque() { |
777 |
head = tail = new Node<E>(null); |
778 |
} |
779 |
|
780 |
/** |
781 |
* Constructs a deque initially containing the elements of |
782 |
* the given collection, added in traversal order of the |
783 |
* collection's iterator. |
784 |
* |
785 |
* @param c the collection of elements to initially contain |
786 |
* @throws NullPointerException if the specified collection or any |
787 |
* of its elements are null |
788 |
*/ |
789 |
public ConcurrentLinkedDeque(Collection<? extends E> c) { |
790 |
// Copy c into a private chain of Nodes |
791 |
Node<E> h = null, t = null; |
792 |
for (E e : c) { |
793 |
Node<E> newNode = new Node<E>(Objects.requireNonNull(e)); |
794 |
if (h == null) |
795 |
h = t = newNode; |
796 |
else { |
797 |
t.lazySetNext(newNode); |
798 |
newNode.lazySetPrev(t); |
799 |
t = newNode; |
800 |
} |
801 |
} |
802 |
initHeadTail(h, t); |
803 |
} |
804 |
|
805 |
/** |
806 |
* Initializes head and tail, ensuring invariants hold. |
807 |
*/ |
808 |
private void initHeadTail(Node<E> h, Node<E> t) { |
809 |
if (h == t) { |
810 |
if (h == null) |
811 |
h = t = new Node<E>(null); |
812 |
else { |
813 |
// Avoid edge case of a single Node with non-null item. |
814 |
Node<E> newNode = new Node<E>(null); |
815 |
t.lazySetNext(newNode); |
816 |
newNode.lazySetPrev(t); |
817 |
t = newNode; |
818 |
} |
819 |
} |
820 |
head = h; |
821 |
tail = t; |
822 |
} |
823 |
|
824 |
/** |
825 |
* Inserts the specified element at the front of this deque. |
826 |
* As the deque is unbounded, this method will never throw |
827 |
* {@link IllegalStateException}. |
828 |
* |
829 |
* @throws NullPointerException if the specified element is null |
830 |
*/ |
831 |
public void addFirst(E e) { |
832 |
linkFirst(e); |
833 |
} |
834 |
|
835 |
/** |
836 |
* Inserts the specified element at the end of this deque. |
837 |
* As the deque is unbounded, this method will never throw |
838 |
* {@link IllegalStateException}. |
839 |
* |
840 |
* <p>This method is equivalent to {@link #add}. |
841 |
* |
842 |
* @throws NullPointerException if the specified element is null |
843 |
*/ |
844 |
public void addLast(E e) { |
845 |
linkLast(e); |
846 |
} |
847 |
|
848 |
/** |
849 |
* Inserts the specified element at the front of this deque. |
850 |
* As the deque is unbounded, this method will never return {@code false}. |
851 |
* |
852 |
* @return {@code true} (as specified by {@link Deque#offerFirst}) |
853 |
* @throws NullPointerException if the specified element is null |
854 |
*/ |
855 |
public boolean offerFirst(E e) { |
856 |
linkFirst(e); |
857 |
return true; |
858 |
} |
859 |
|
860 |
/** |
861 |
* Inserts the specified element at the end of this deque. |
862 |
* As the deque is unbounded, this method will never return {@code false}. |
863 |
* |
864 |
* <p>This method is equivalent to {@link #add}. |
865 |
* |
866 |
* @return {@code true} (as specified by {@link Deque#offerLast}) |
867 |
* @throws NullPointerException if the specified element is null |
868 |
*/ |
869 |
public boolean offerLast(E e) { |
870 |
linkLast(e); |
871 |
return true; |
872 |
} |
873 |
|
874 |
public E peekFirst() { |
875 |
restart: for (;;) { |
876 |
E item; |
877 |
Node<E> first = first(), p = first; |
878 |
while ((item = p.item) == null) { |
879 |
if (p == (p = p.next)) continue restart; |
880 |
if (p == null) |
881 |
break; |
882 |
} |
883 |
// recheck for linearizability |
884 |
if (first.prev != null) continue restart; |
885 |
return item; |
886 |
} |
887 |
} |
888 |
|
889 |
public E peekLast() { |
890 |
restart: for (;;) { |
891 |
E item; |
892 |
Node<E> last = last(), p = last; |
893 |
while ((item = p.item) == null) { |
894 |
if (p == (p = p.prev)) continue restart; |
895 |
if (p == null) |
896 |
break; |
897 |
} |
898 |
// recheck for linearizability |
899 |
if (last.next != null) continue restart; |
900 |
return item; |
901 |
} |
902 |
} |
903 |
|
904 |
/** |
905 |
* @throws NoSuchElementException {@inheritDoc} |
906 |
*/ |
907 |
public E getFirst() { |
908 |
return screenNullResult(peekFirst()); |
909 |
} |
910 |
|
911 |
/** |
912 |
* @throws NoSuchElementException {@inheritDoc} |
913 |
*/ |
914 |
public E getLast() { |
915 |
return screenNullResult(peekLast()); |
916 |
} |
917 |
|
918 |
public E pollFirst() { |
919 |
restart: for (;;) { |
920 |
for (Node<E> first = first(), p = first;;) { |
921 |
final E item; |
922 |
if ((item = p.item) != null) { |
923 |
// recheck for linearizability |
924 |
if (first.prev != null) continue restart; |
925 |
if (p.casItem(item, null)) { |
926 |
unlink(p); |
927 |
return item; |
928 |
} |
929 |
} |
930 |
if (p == (p = p.next)) continue restart; |
931 |
if (p == null) { |
932 |
if (first.prev != null) continue restart; |
933 |
return null; |
934 |
} |
935 |
} |
936 |
} |
937 |
} |
938 |
|
939 |
public E pollLast() { |
940 |
restart: for (;;) { |
941 |
for (Node<E> last = last(), p = last;;) { |
942 |
final E item; |
943 |
if ((item = p.item) != null) { |
944 |
// recheck for linearizability |
945 |
if (last.next != null) continue restart; |
946 |
if (p.casItem(item, null)) { |
947 |
unlink(p); |
948 |
return item; |
949 |
} |
950 |
} |
951 |
if (p == (p = p.prev)) continue restart; |
952 |
if (p == null) { |
953 |
if (last.next != null) continue restart; |
954 |
return null; |
955 |
} |
956 |
} |
957 |
} |
958 |
} |
959 |
|
960 |
/** |
961 |
* @throws NoSuchElementException {@inheritDoc} |
962 |
*/ |
963 |
public E removeFirst() { |
964 |
return screenNullResult(pollFirst()); |
965 |
} |
966 |
|
967 |
/** |
968 |
* @throws NoSuchElementException {@inheritDoc} |
969 |
*/ |
970 |
public E removeLast() { |
971 |
return screenNullResult(pollLast()); |
972 |
} |
973 |
|
974 |
// *** Queue and stack methods *** |
975 |
|
976 |
/** |
977 |
* Inserts the specified element at the tail of this deque. |
978 |
* As the deque is unbounded, this method will never return {@code false}. |
979 |
* |
980 |
* @return {@code true} (as specified by {@link Queue#offer}) |
981 |
* @throws NullPointerException if the specified element is null |
982 |
*/ |
983 |
public boolean offer(E e) { |
984 |
return offerLast(e); |
985 |
} |
986 |
|
987 |
/** |
988 |
* Inserts the specified element at the tail of this deque. |
989 |
* As the deque is unbounded, this method will never throw |
990 |
* {@link IllegalStateException} or return {@code false}. |
991 |
* |
992 |
* @return {@code true} (as specified by {@link Collection#add}) |
993 |
* @throws NullPointerException if the specified element is null |
994 |
*/ |
995 |
public boolean add(E e) { |
996 |
return offerLast(e); |
997 |
} |
998 |
|
999 |
public E poll() { return pollFirst(); } |
1000 |
public E peek() { return peekFirst(); } |
1001 |
|
1002 |
/** |
1003 |
* @throws NoSuchElementException {@inheritDoc} |
1004 |
*/ |
1005 |
public E remove() { return removeFirst(); } |
1006 |
|
1007 |
/** |
1008 |
* @throws NoSuchElementException {@inheritDoc} |
1009 |
*/ |
1010 |
public E pop() { return removeFirst(); } |
1011 |
|
1012 |
/** |
1013 |
* @throws NoSuchElementException {@inheritDoc} |
1014 |
*/ |
1015 |
public E element() { return getFirst(); } |
1016 |
|
1017 |
/** |
1018 |
* @throws NullPointerException {@inheritDoc} |
1019 |
*/ |
1020 |
public void push(E e) { addFirst(e); } |
1021 |
|
1022 |
/** |
1023 |
* Removes the first occurrence of the specified element from this deque. |
1024 |
* If the deque does not contain the element, it is unchanged. |
1025 |
* More formally, removes the first element {@code e} such that |
1026 |
* {@code o.equals(e)} (if such an element exists). |
1027 |
* Returns {@code true} if this deque contained the specified element |
1028 |
* (or equivalently, if this deque changed as a result of the call). |
1029 |
* |
1030 |
* @param o element to be removed from this deque, if present |
1031 |
* @return {@code true} if the deque contained the specified element |
1032 |
* @throws NullPointerException if the specified element is null |
1033 |
*/ |
1034 |
public boolean removeFirstOccurrence(Object o) { |
1035 |
Objects.requireNonNull(o); |
1036 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
1037 |
E item = p.item; |
1038 |
if (item != null && o.equals(item) && p.casItem(item, null)) { |
1039 |
unlink(p); |
1040 |
return true; |
1041 |
} |
1042 |
} |
1043 |
return false; |
1044 |
} |
1045 |
|
1046 |
/** |
1047 |
* Removes the last occurrence of the specified element from this deque. |
1048 |
* If the deque does not contain the element, it is unchanged. |
1049 |
* More formally, removes the last element {@code e} such that |
1050 |
* {@code o.equals(e)} (if such an element exists). |
1051 |
* Returns {@code true} if this deque contained the specified element |
1052 |
* (or equivalently, if this deque changed as a result of the call). |
1053 |
* |
1054 |
* @param o element to be removed from this deque, if present |
1055 |
* @return {@code true} if the deque contained the specified element |
1056 |
* @throws NullPointerException if the specified element is null |
1057 |
*/ |
1058 |
public boolean removeLastOccurrence(Object o) { |
1059 |
Objects.requireNonNull(o); |
1060 |
for (Node<E> p = last(); p != null; p = pred(p)) { |
1061 |
E item = p.item; |
1062 |
if (item != null && o.equals(item) && p.casItem(item, null)) { |
1063 |
unlink(p); |
1064 |
return true; |
1065 |
} |
1066 |
} |
1067 |
return false; |
1068 |
} |
1069 |
|
1070 |
/** |
1071 |
* Returns {@code true} if this deque contains the specified element. |
1072 |
* More formally, returns {@code true} if and only if this deque contains |
1073 |
* at least one element {@code e} such that {@code o.equals(e)}. |
1074 |
* |
1075 |
* @param o element whose presence in this deque is to be tested |
1076 |
* @return {@code true} if this deque contains the specified element |
1077 |
*/ |
1078 |
public boolean contains(Object o) { |
1079 |
if (o != null) { |
1080 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
1081 |
E item = p.item; |
1082 |
if (item != null && o.equals(item)) |
1083 |
return true; |
1084 |
} |
1085 |
} |
1086 |
return false; |
1087 |
} |
1088 |
|
1089 |
/** |
1090 |
* Returns {@code true} if this collection contains no elements. |
1091 |
* |
1092 |
* @return {@code true} if this collection contains no elements |
1093 |
*/ |
1094 |
public boolean isEmpty() { |
1095 |
return peekFirst() == null; |
1096 |
} |
1097 |
|
1098 |
/** |
1099 |
* Returns the number of elements in this deque. If this deque |
1100 |
* contains more than {@code Integer.MAX_VALUE} elements, it |
1101 |
* returns {@code Integer.MAX_VALUE}. |
1102 |
* |
1103 |
* <p>Beware that, unlike in most collections, this method is |
1104 |
* <em>NOT</em> a constant-time operation. Because of the |
1105 |
* asynchronous nature of these deques, determining the current |
1106 |
* number of elements requires traversing them all to count them. |
1107 |
* Additionally, it is possible for the size to change during |
1108 |
* execution of this method, in which case the returned result |
1109 |
* will be inaccurate. Thus, this method is typically not very |
1110 |
* useful in concurrent applications. |
1111 |
* |
1112 |
* @return the number of elements in this deque |
1113 |
*/ |
1114 |
public int size() { |
1115 |
restartFromHead: for (;;) { |
1116 |
int count = 0; |
1117 |
for (Node<E> p = first(); p != null;) { |
1118 |
if (p.item != null) |
1119 |
if (++count == Integer.MAX_VALUE) |
1120 |
break; // @see Collection.size() |
1121 |
if (p == (p = p.next)) |
1122 |
continue restartFromHead; |
1123 |
} |
1124 |
return count; |
1125 |
} |
1126 |
} |
1127 |
|
1128 |
/** |
1129 |
* Removes the first occurrence of the specified element from this deque. |
1130 |
* If the deque does not contain the element, it is unchanged. |
1131 |
* More formally, removes the first element {@code e} such that |
1132 |
* {@code o.equals(e)} (if such an element exists). |
1133 |
* Returns {@code true} if this deque contained the specified element |
1134 |
* (or equivalently, if this deque changed as a result of the call). |
1135 |
* |
1136 |
* <p>This method is equivalent to {@link #removeFirstOccurrence(Object)}. |
1137 |
* |
1138 |
* @param o element to be removed from this deque, if present |
1139 |
* @return {@code true} if the deque contained the specified element |
1140 |
* @throws NullPointerException if the specified element is null |
1141 |
*/ |
1142 |
public boolean remove(Object o) { |
1143 |
return removeFirstOccurrence(o); |
1144 |
} |
1145 |
|
1146 |
/** |
1147 |
* Appends all of the elements in the specified collection to the end of |
1148 |
* this deque, in the order that they are returned by the specified |
1149 |
* collection's iterator. Attempts to {@code addAll} of a deque to |
1150 |
* itself result in {@code IllegalArgumentException}. |
1151 |
* |
1152 |
* @param c the elements to be inserted into this deque |
1153 |
* @return {@code true} if this deque changed as a result of the call |
1154 |
* @throws NullPointerException if the specified collection or any |
1155 |
* of its elements are null |
1156 |
* @throws IllegalArgumentException if the collection is this deque |
1157 |
*/ |
1158 |
public boolean addAll(Collection<? extends E> c) { |
1159 |
if (c == this) |
1160 |
// As historically specified in AbstractQueue#addAll |
1161 |
throw new IllegalArgumentException(); |
1162 |
|
1163 |
// Copy c into a private chain of Nodes |
1164 |
Node<E> beginningOfTheEnd = null, last = null; |
1165 |
for (E e : c) { |
1166 |
Node<E> newNode = new Node<E>(Objects.requireNonNull(e)); |
1167 |
if (beginningOfTheEnd == null) |
1168 |
beginningOfTheEnd = last = newNode; |
1169 |
else { |
1170 |
last.lazySetNext(newNode); |
1171 |
newNode.lazySetPrev(last); |
1172 |
last = newNode; |
1173 |
} |
1174 |
} |
1175 |
if (beginningOfTheEnd == null) |
1176 |
return false; |
1177 |
|
1178 |
// Atomically append the chain at the tail of this collection |
1179 |
restartFromTail: |
1180 |
for (;;) |
1181 |
for (Node<E> t = tail, p = t, q;;) { |
1182 |
if ((q = p.next) != null && |
1183 |
(q = (p = q).next) != null) |
1184 |
// Check for tail updates every other hop. |
1185 |
// If p == q, we are sure to follow tail instead. |
1186 |
p = (t != (t = tail)) ? t : q; |
1187 |
else if (p.prev == p) // NEXT_TERMINATOR |
1188 |
continue restartFromTail; |
1189 |
else { |
1190 |
// p is last node |
1191 |
beginningOfTheEnd.lazySetPrev(p); // CAS piggyback |
1192 |
if (p.casNext(null, beginningOfTheEnd)) { |
1193 |
// Successful CAS is the linearization point |
1194 |
// for all elements to be added to this deque. |
1195 |
if (!casTail(t, last)) { |
1196 |
// Try a little harder to update tail, |
1197 |
// since we may be adding many elements. |
1198 |
t = tail; |
1199 |
if (last.next == null) |
1200 |
casTail(t, last); |
1201 |
} |
1202 |
return true; |
1203 |
} |
1204 |
// Lost CAS race to another thread; re-read next |
1205 |
} |
1206 |
} |
1207 |
} |
1208 |
|
1209 |
/** |
1210 |
* Removes all of the elements from this deque. |
1211 |
*/ |
1212 |
public void clear() { |
1213 |
while (pollFirst() != null) |
1214 |
; |
1215 |
} |
1216 |
|
1217 |
public String toString() { |
1218 |
String[] a = null; |
1219 |
restartFromHead: for (;;) { |
1220 |
int charLength = 0; |
1221 |
int size = 0; |
1222 |
for (Node<E> p = first(); p != null;) { |
1223 |
E item = p.item; |
1224 |
if (item != null) { |
1225 |
if (a == null) |
1226 |
a = new String[4]; |
1227 |
else if (size == a.length) |
1228 |
a = Arrays.copyOf(a, 2 * size); |
1229 |
String s = item.toString(); |
1230 |
a[size++] = s; |
1231 |
charLength += s.length(); |
1232 |
} |
1233 |
if (p == (p = p.next)) |
1234 |
continue restartFromHead; |
1235 |
} |
1236 |
|
1237 |
if (size == 0) |
1238 |
return "[]"; |
1239 |
|
1240 |
return Helpers.toString(a, size, charLength); |
1241 |
} |
1242 |
} |
1243 |
|
1244 |
private Object[] toArrayInternal(Object[] a) { |
1245 |
Object[] x = a; |
1246 |
restartFromHead: for (;;) { |
1247 |
int size = 0; |
1248 |
for (Node<E> p = first(); p != null;) { |
1249 |
E item = p.item; |
1250 |
if (item != null) { |
1251 |
if (x == null) |
1252 |
x = new Object[4]; |
1253 |
else if (size == x.length) |
1254 |
x = Arrays.copyOf(x, 2 * (size + 4)); |
1255 |
x[size++] = item; |
1256 |
} |
1257 |
if (p == (p = p.next)) |
1258 |
continue restartFromHead; |
1259 |
} |
1260 |
if (x == null) |
1261 |
return new Object[0]; |
1262 |
else if (a != null && size <= a.length) { |
1263 |
if (a != x) |
1264 |
System.arraycopy(x, 0, a, 0, size); |
1265 |
if (size < a.length) |
1266 |
a[size] = null; |
1267 |
return a; |
1268 |
} |
1269 |
return (size == x.length) ? x : Arrays.copyOf(x, size); |
1270 |
} |
1271 |
} |
1272 |
|
1273 |
/** |
1274 |
* Returns an array containing all of the elements in this deque, in |
1275 |
* proper sequence (from first to last element). |
1276 |
* |
1277 |
* <p>The returned array will be "safe" in that no references to it are |
1278 |
* maintained by this deque. (In other words, this method must allocate |
1279 |
* a new array). The caller is thus free to modify the returned array. |
1280 |
* |
1281 |
* <p>This method acts as bridge between array-based and collection-based |
1282 |
* APIs. |
1283 |
* |
1284 |
* @return an array containing all of the elements in this deque |
1285 |
*/ |
1286 |
public Object[] toArray() { |
1287 |
return toArrayInternal(null); |
1288 |
} |
1289 |
|
1290 |
/** |
1291 |
* Returns an array containing all of the elements in this deque, |
1292 |
* in proper sequence (from first to last element); the runtime |
1293 |
* type of the returned array is that of the specified array. If |
1294 |
* the deque fits in the specified array, it is returned therein. |
1295 |
* Otherwise, a new array is allocated with the runtime type of |
1296 |
* the specified array and the size of this deque. |
1297 |
* |
1298 |
* <p>If this deque fits in the specified array with room to spare |
1299 |
* (i.e., the array has more elements than this deque), the element in |
1300 |
* the array immediately following the end of the deque is set to |
1301 |
* {@code null}. |
1302 |
* |
1303 |
* <p>Like the {@link #toArray()} method, this method acts as |
1304 |
* bridge between array-based and collection-based APIs. Further, |
1305 |
* this method allows precise control over the runtime type of the |
1306 |
* output array, and may, under certain circumstances, be used to |
1307 |
* save allocation costs. |
1308 |
* |
1309 |
* <p>Suppose {@code x} is a deque known to contain only strings. |
1310 |
* The following code can be used to dump the deque into a newly |
1311 |
* allocated array of {@code String}: |
1312 |
* |
1313 |
* <pre> {@code String[] y = x.toArray(new String[0]);}</pre> |
1314 |
* |
1315 |
* Note that {@code toArray(new Object[0])} is identical in function to |
1316 |
* {@code toArray()}. |
1317 |
* |
1318 |
* @param a the array into which the elements of the deque are to |
1319 |
* be stored, if it is big enough; otherwise, a new array of the |
1320 |
* same runtime type is allocated for this purpose |
1321 |
* @return an array containing all of the elements in this deque |
1322 |
* @throws ArrayStoreException if the runtime type of the specified array |
1323 |
* is not a supertype of the runtime type of every element in |
1324 |
* this deque |
1325 |
* @throws NullPointerException if the specified array is null |
1326 |
*/ |
1327 |
@SuppressWarnings("unchecked") |
1328 |
public <T> T[] toArray(T[] a) { |
1329 |
if (a == null) throw new NullPointerException(); |
1330 |
return (T[]) toArrayInternal(a); |
1331 |
} |
1332 |
|
1333 |
/** |
1334 |
* Returns an iterator over the elements in this deque in proper sequence. |
1335 |
* The elements will be returned in order from first (head) to last (tail). |
1336 |
* |
1337 |
* <p>The returned iterator is |
1338 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
1339 |
* |
1340 |
* @return an iterator over the elements in this deque in proper sequence |
1341 |
*/ |
1342 |
public Iterator<E> iterator() { |
1343 |
return new Itr(); |
1344 |
} |
1345 |
|
1346 |
/** |
1347 |
* Returns an iterator over the elements in this deque in reverse |
1348 |
* sequential order. The elements will be returned in order from |
1349 |
* last (tail) to first (head). |
1350 |
* |
1351 |
* <p>The returned iterator is |
1352 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
1353 |
* |
1354 |
* @return an iterator over the elements in this deque in reverse order |
1355 |
*/ |
1356 |
public Iterator<E> descendingIterator() { |
1357 |
return new DescendingItr(); |
1358 |
} |
1359 |
|
1360 |
private abstract class AbstractItr implements Iterator<E> { |
1361 |
/** |
1362 |
* Next node to return item for. |
1363 |
*/ |
1364 |
private Node<E> nextNode; |
1365 |
|
1366 |
/** |
1367 |
* nextItem holds on to item fields because once we claim |
1368 |
* that an element exists in hasNext(), we must return it in |
1369 |
* the following next() call even if it was in the process of |
1370 |
* being removed when hasNext() was called. |
1371 |
*/ |
1372 |
private E nextItem; |
1373 |
|
1374 |
/** |
1375 |
* Node returned by most recent call to next. Needed by remove. |
1376 |
* Reset to null if this element is deleted by a call to remove. |
1377 |
*/ |
1378 |
private Node<E> lastRet; |
1379 |
|
1380 |
abstract Node<E> startNode(); |
1381 |
abstract Node<E> nextNode(Node<E> p); |
1382 |
|
1383 |
AbstractItr() { |
1384 |
advance(); |
1385 |
} |
1386 |
|
1387 |
/** |
1388 |
* Sets nextNode and nextItem to next valid node, or to null |
1389 |
* if no such. |
1390 |
*/ |
1391 |
private void advance() { |
1392 |
lastRet = nextNode; |
1393 |
|
1394 |
Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode); |
1395 |
for (;; p = nextNode(p)) { |
1396 |
if (p == null) { |
1397 |
// might be at active end or TERMINATOR node; both are OK |
1398 |
nextNode = null; |
1399 |
nextItem = null; |
1400 |
break; |
1401 |
} |
1402 |
E item = p.item; |
1403 |
if (item != null) { |
1404 |
nextNode = p; |
1405 |
nextItem = item; |
1406 |
break; |
1407 |
} |
1408 |
} |
1409 |
} |
1410 |
|
1411 |
public boolean hasNext() { |
1412 |
return nextItem != null; |
1413 |
} |
1414 |
|
1415 |
public E next() { |
1416 |
E item = nextItem; |
1417 |
if (item == null) throw new NoSuchElementException(); |
1418 |
advance(); |
1419 |
return item; |
1420 |
} |
1421 |
|
1422 |
public void remove() { |
1423 |
Node<E> l = lastRet; |
1424 |
if (l == null) throw new IllegalStateException(); |
1425 |
l.item = null; |
1426 |
unlink(l); |
1427 |
lastRet = null; |
1428 |
} |
1429 |
} |
1430 |
|
1431 |
/** Forward iterator */ |
1432 |
private class Itr extends AbstractItr { |
1433 |
Node<E> startNode() { return first(); } |
1434 |
Node<E> nextNode(Node<E> p) { return succ(p); } |
1435 |
} |
1436 |
|
1437 |
/** Descending iterator */ |
1438 |
private class DescendingItr extends AbstractItr { |
1439 |
Node<E> startNode() { return last(); } |
1440 |
Node<E> nextNode(Node<E> p) { return pred(p); } |
1441 |
} |
1442 |
|
1443 |
/** A customized variant of Spliterators.IteratorSpliterator */ |
1444 |
static final class CLDSpliterator<E> implements Spliterator<E> { |
1445 |
static final int MAX_BATCH = 1 << 25; // max batch array size; |
1446 |
final ConcurrentLinkedDeque<E> queue; |
1447 |
Node<E> current; // current node; null until initialized |
1448 |
int batch; // batch size for splits |
1449 |
boolean exhausted; // true when no more nodes |
1450 |
CLDSpliterator(ConcurrentLinkedDeque<E> queue) { |
1451 |
this.queue = queue; |
1452 |
} |
1453 |
|
1454 |
public Spliterator<E> trySplit() { |
1455 |
Node<E> p; |
1456 |
final ConcurrentLinkedDeque<E> q = this.queue; |
1457 |
int b = batch; |
1458 |
int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1; |
1459 |
if (!exhausted && |
1460 |
((p = current) != null || (p = q.first()) != null)) { |
1461 |
if (p.item == null && p == (p = p.next)) |
1462 |
current = p = q.first(); |
1463 |
if (p != null && p.next != null) { |
1464 |
Object[] a = new Object[n]; |
1465 |
int i = 0; |
1466 |
do { |
1467 |
if ((a[i] = p.item) != null) |
1468 |
++i; |
1469 |
if (p == (p = p.next)) |
1470 |
p = q.first(); |
1471 |
} while (p != null && i < n); |
1472 |
if ((current = p) == null) |
1473 |
exhausted = true; |
1474 |
if (i > 0) { |
1475 |
batch = i; |
1476 |
return Spliterators.spliterator |
1477 |
(a, 0, i, (Spliterator.ORDERED | |
1478 |
Spliterator.NONNULL | |
1479 |
Spliterator.CONCURRENT)); |
1480 |
} |
1481 |
} |
1482 |
} |
1483 |
return null; |
1484 |
} |
1485 |
|
1486 |
public void forEachRemaining(Consumer<? super E> action) { |
1487 |
Node<E> p; |
1488 |
if (action == null) throw new NullPointerException(); |
1489 |
final ConcurrentLinkedDeque<E> q = this.queue; |
1490 |
if (!exhausted && |
1491 |
((p = current) != null || (p = q.first()) != null)) { |
1492 |
exhausted = true; |
1493 |
do { |
1494 |
E e = p.item; |
1495 |
if (p == (p = p.next)) |
1496 |
p = q.first(); |
1497 |
if (e != null) |
1498 |
action.accept(e); |
1499 |
} while (p != null); |
1500 |
} |
1501 |
} |
1502 |
|
1503 |
public boolean tryAdvance(Consumer<? super E> action) { |
1504 |
Node<E> p; |
1505 |
if (action == null) throw new NullPointerException(); |
1506 |
final ConcurrentLinkedDeque<E> q = this.queue; |
1507 |
if (!exhausted && |
1508 |
((p = current) != null || (p = q.first()) != null)) { |
1509 |
E e; |
1510 |
do { |
1511 |
e = p.item; |
1512 |
if (p == (p = p.next)) |
1513 |
p = q.first(); |
1514 |
} while (e == null && p != null); |
1515 |
if ((current = p) == null) |
1516 |
exhausted = true; |
1517 |
if (e != null) { |
1518 |
action.accept(e); |
1519 |
return true; |
1520 |
} |
1521 |
} |
1522 |
return false; |
1523 |
} |
1524 |
|
1525 |
public long estimateSize() { return Long.MAX_VALUE; } |
1526 |
|
1527 |
public int characteristics() { |
1528 |
return Spliterator.ORDERED | Spliterator.NONNULL | |
1529 |
Spliterator.CONCURRENT; |
1530 |
} |
1531 |
} |
1532 |
|
1533 |
/** |
1534 |
* Returns a {@link Spliterator} over the elements in this deque. |
1535 |
* |
1536 |
* <p>The returned spliterator is |
1537 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
1538 |
* |
1539 |
* <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT}, |
1540 |
* {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}. |
1541 |
* |
1542 |
* @implNote |
1543 |
* The {@code Spliterator} implements {@code trySplit} to permit limited |
1544 |
* parallelism. |
1545 |
* |
1546 |
* @return a {@code Spliterator} over the elements in this deque |
1547 |
* @since 1.8 |
1548 |
*/ |
1549 |
public Spliterator<E> spliterator() { |
1550 |
return new CLDSpliterator<E>(this); |
1551 |
} |
1552 |
|
1553 |
/** |
1554 |
* Saves this deque to a stream (that is, serializes it). |
1555 |
* |
1556 |
* @param s the stream |
1557 |
* @throws java.io.IOException if an I/O error occurs |
1558 |
* @serialData All of the elements (each an {@code E}) in |
1559 |
* the proper order, followed by a null |
1560 |
*/ |
1561 |
private void writeObject(java.io.ObjectOutputStream s) |
1562 |
throws java.io.IOException { |
1563 |
|
1564 |
// Write out any hidden stuff |
1565 |
s.defaultWriteObject(); |
1566 |
|
1567 |
// Write out all elements in the proper order. |
1568 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
1569 |
E item = p.item; |
1570 |
if (item != null) |
1571 |
s.writeObject(item); |
1572 |
} |
1573 |
|
1574 |
// Use trailing null as sentinel |
1575 |
s.writeObject(null); |
1576 |
} |
1577 |
|
1578 |
/** |
1579 |
* Reconstitutes this deque from a stream (that is, deserializes it). |
1580 |
* @param s the stream |
1581 |
* @throws ClassNotFoundException if the class of a serialized object |
1582 |
* could not be found |
1583 |
* @throws java.io.IOException if an I/O error occurs |
1584 |
*/ |
1585 |
private void readObject(java.io.ObjectInputStream s) |
1586 |
throws java.io.IOException, ClassNotFoundException { |
1587 |
s.defaultReadObject(); |
1588 |
|
1589 |
// Read in elements until trailing null sentinel found |
1590 |
Node<E> h = null, t = null; |
1591 |
for (Object item; (item = s.readObject()) != null; ) { |
1592 |
@SuppressWarnings("unchecked") |
1593 |
Node<E> newNode = new Node<E>((E) item); |
1594 |
if (h == null) |
1595 |
h = t = newNode; |
1596 |
else { |
1597 |
t.lazySetNext(newNode); |
1598 |
newNode.lazySetPrev(t); |
1599 |
t = newNode; |
1600 |
} |
1601 |
} |
1602 |
initHeadTail(h, t); |
1603 |
} |
1604 |
|
1605 |
private boolean casHead(Node<E> cmp, Node<E> val) { |
1606 |
return U.compareAndSwapObject(this, HEAD, cmp, val); |
1607 |
} |
1608 |
|
1609 |
private boolean casTail(Node<E> cmp, Node<E> val) { |
1610 |
return U.compareAndSwapObject(this, TAIL, cmp, val); |
1611 |
} |
1612 |
|
1613 |
// Unsafe mechanics |
1614 |
|
1615 |
private static final sun.misc.Unsafe U = sun.misc.Unsafe.getUnsafe(); |
1616 |
private static final long HEAD; |
1617 |
private static final long TAIL; |
1618 |
static { |
1619 |
PREV_TERMINATOR = new Node<Object>(); |
1620 |
PREV_TERMINATOR.next = PREV_TERMINATOR; |
1621 |
NEXT_TERMINATOR = new Node<Object>(); |
1622 |
NEXT_TERMINATOR.prev = NEXT_TERMINATOR; |
1623 |
try { |
1624 |
HEAD = U.objectFieldOffset |
1625 |
(ConcurrentLinkedDeque.class.getDeclaredField("head")); |
1626 |
TAIL = U.objectFieldOffset |
1627 |
(ConcurrentLinkedDeque.class.getDeclaredField("tail")); |
1628 |
} catch (ReflectiveOperationException e) { |
1629 |
throw new Error(e); |
1630 |
} |
1631 |
} |
1632 |
} |