1 |
/* |
2 |
* Written by Doug Lea and Martin Buchholz with assistance from members of |
3 |
* JCP JSR-166 Expert Group and released to the public domain, as explained |
4 |
* at http://creativecommons.org/licenses/publicdomain |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
|
9 |
import java.util.AbstractCollection; |
10 |
import java.util.ArrayList; |
11 |
import java.util.Collection; |
12 |
import java.util.Deque; |
13 |
import java.util.Iterator; |
14 |
import java.util.ConcurrentModificationException; |
15 |
import java.util.NoSuchElementException; |
16 |
import java.util.concurrent.atomic.AtomicReference; |
17 |
|
18 |
/** |
19 |
* A concurrent linked-list implementation of a {@link Deque} |
20 |
* (double-ended queue). Concurrent insertion, removal, and access |
21 |
* operations execute safely across multiple threads. Iterators are |
22 |
* <i>weakly consistent</i>, returning elements reflecting the state |
23 |
* of the deque at some point at or since the creation of the |
24 |
* iterator. They do <em>not</em> throw {@link |
25 |
* ConcurrentModificationException}, and may proceed concurrently with |
26 |
* other operations. |
27 |
* |
28 |
* <p>This class and its iterators implement all of the |
29 |
* <em>optional</em> methods of the {@link Collection} and {@link |
30 |
* Iterator} interfaces. Like most other concurrent collection |
31 |
* implementations, this class does not permit the use of |
32 |
* {@code null} elements. because some null arguments and return |
33 |
* values cannot be reliably distinguished from the absence of |
34 |
* elements. Arbitrarily, the {@link Collection#remove} method is |
35 |
* mapped to {@code removeFirstOccurrence}, and {@link |
36 |
* Collection#add} is mapped to {@code addLast}. |
37 |
* |
38 |
* <p>Beware that, unlike in most collections, the {@link #size} |
39 |
* method is <em>NOT</em> a constant-time operation. Because of the |
40 |
* asynchronous nature of these deques, determining the current number |
41 |
* of elements requires traversing them all to count them. |
42 |
* Additionally, it is possible for the size to change during |
43 |
* execution of this method, in which case the returned result will be |
44 |
* inaccurate. Thus, this method is typically not very useful in |
45 |
* concurrent applications. |
46 |
* |
47 |
* <p>This class is {@code Serializable}, but relies on default |
48 |
* serialization mechanisms. Usually, it is a better idea for any |
49 |
* serializable class using a {@code ConcurrentLinkedDeque} to instead |
50 |
* serialize a snapshot of the elements obtained by method |
51 |
* {@code toArray}. |
52 |
* |
53 |
* @author Doug Lea |
54 |
* @author Martin Buchholz |
55 |
* @param <E> the type of elements held in this collection |
56 |
*/ |
57 |
|
58 |
public class ConcurrentLinkedDeque<E> |
59 |
extends AbstractCollection<E> |
60 |
implements Deque<E>, java.io.Serializable { |
61 |
|
62 |
/* |
63 |
* This is an implementation of a concurrent lock-free deque |
64 |
* supporting interior removes but not interior insertions, as |
65 |
* required to fully support the Deque interface. |
66 |
* |
67 |
* We extend the techniques developed for |
68 |
* ConcurrentLinkedQueue and LinkedTransferQueue |
69 |
* (see the internal docs for those classes). |
70 |
* |
71 |
* At any time, there is precisely one "first" active node with a |
72 |
* null prev pointer. Similarly there is one "last" active node |
73 |
* with a null next pointer. New nodes are simply enqueued by |
74 |
* null-CASing. |
75 |
* |
76 |
* A node p is considered "active" if it either contains an |
77 |
* element, or is an end node and neither next nor prev pointers |
78 |
* are self-links: |
79 |
* |
80 |
* p.item != null || |
81 |
* (p.prev == null && p.next != p) || |
82 |
* (p.next == null && p.prev != p) |
83 |
* |
84 |
* The head and tail pointers are only approximations to the start |
85 |
* and end of the deque. The first node can always be found by |
86 |
* following prev pointers from head; likewise for tail. However, |
87 |
* head and tail may be pointing at deleted nodes that have been |
88 |
* unlinked and so may not be reachable from any live node. |
89 |
* |
90 |
* There are 3 levels of node deletion: |
91 |
* - logical deletion atomically removes the element |
92 |
* - "unlinking" makes a deleted node unreachable from active |
93 |
* nodes, and thus eventually reclaimable by GC |
94 |
* - "gc-unlinking" further does the reverse of making active |
95 |
* nodes unreachable from deleted nodes, making it easier for |
96 |
* the GC to reclaim future deleted nodes |
97 |
* |
98 |
* TODO: find a better name for "gc-unlinked" |
99 |
* |
100 |
* Logical deletion of a node simply involves CASing its element |
101 |
* to null. Physical deletion is merely an optimization (albeit a |
102 |
* critical one), and can be performed at our convenience. At any |
103 |
* time, the set of non-logically-deleted nodes maintained by prev |
104 |
* and next links are identical, that is the live elements found |
105 |
* via next links from the first node is equal to the elements |
106 |
* found via prev links from the last node. However, this is not |
107 |
* true for nodes that have already been logically deleted - such |
108 |
* nodes may only be reachable in one direction. |
109 |
* |
110 |
* When a node is dequeued at either end, e.g. via poll(), we |
111 |
* would like to break any references from the node to live nodes, |
112 |
* to stop old garbage from causing retention of new garbage with |
113 |
* a generational or conservative GC. We develop further the |
114 |
* self-linking trick that was very effective in other concurrent |
115 |
* collection classes. The idea is to replace prev and next |
116 |
* pointers to active nodes with special values that are |
117 |
* interpreted to mean off-the-list-at-one-end. These are |
118 |
* approximations, but good enough to preserve the properties we |
119 |
* want in our traversals, e.g. we guarantee that a traversal will |
120 |
* never hit the same element twice, but we don't guarantee |
121 |
* whether a traversal that runs out of elements will be able to |
122 |
* see more elements later after more elements are added at that |
123 |
* end. Doing gc-unlinking safely is particularly tricky, since |
124 |
* any node can be in use indefinitely (for example by an |
125 |
* iterator). We must make sure that the nodes pointed at by |
126 |
* head/tail do not get gc-unlinked, since head/tail are needed to |
127 |
* get "back on track" by other nodes that are gc-unlinked. |
128 |
* gc-unlinking accounts for much of the implementation complexity. |
129 |
* |
130 |
* Since neither unlinking nor gc-unlinking are necessary for |
131 |
* correctness, there are many implementation choices regarding |
132 |
* frequency (eagerness) of these operations. Since volatile |
133 |
* reads are likely to be much cheaper than CASes, saving CASes by |
134 |
* unlinking multiple adjacent nodes at a time may be a win. |
135 |
* gc-unlinking can be performed rarely and still be effective, |
136 |
* since it is most important that long chains of deleted nodes |
137 |
* are occasionally broken. |
138 |
* |
139 |
* The actual representation we use is that p.next == p means to |
140 |
* goto the first node, and p.next == null && p.prev == p means |
141 |
* that the iteration is at an end and that p is a (final static) |
142 |
* dummy node, NEXT_TERMINATOR, and not the last active node. |
143 |
* Finishing the iteration when encountering such a TERMINATOR is |
144 |
* good enough for read-only traversals. When the last active |
145 |
* node is desired, for example when enqueueing, goto tail and |
146 |
* continue traversal. |
147 |
* |
148 |
* The implementation is completely directionally symmetrical, |
149 |
* except that most public methods that iterate through the list |
150 |
* follow next pointers ("forward" direction). |
151 |
* |
152 |
* There is one desirable property we would like to have, but |
153 |
* don't: it is possible, when an addFirst(A) is racing with |
154 |
* pollFirst() removing B, for an iterating observer to see A B C |
155 |
* and subsequently see A C, even though no interior removes are |
156 |
* ever performed. I believe this wart can only be removed at |
157 |
* significant runtime cost. |
158 |
* |
159 |
* Empirically, microbenchmarks suggest that this class adds about |
160 |
* 40% overhead relative to ConcurrentLinkedQueue, which feels as |
161 |
* good as we can hope for. |
162 |
*/ |
163 |
|
164 |
/** |
165 |
* A node from which the first node on list (that is, the unique |
166 |
* node with node.prev == null) can be reached in O(1) time. |
167 |
* Invariants: |
168 |
* - the first node is always O(1) reachable from head via prev links |
169 |
* - all live nodes are reachable from the first node via succ() |
170 |
* - head != null |
171 |
* - (tmp = head).next != tmp || tmp != head |
172 |
* Non-invariants: |
173 |
* - head.item may or may not be null |
174 |
* - head may not be reachable from the first or last node, or from tail |
175 |
*/ |
176 |
private transient volatile Node<E> head = new Node<E>(null); |
177 |
|
178 |
private final static Node<Object> PREV_TERMINATOR, NEXT_TERMINATOR; |
179 |
|
180 |
static { |
181 |
PREV_TERMINATOR = new Node<Object>(null); |
182 |
PREV_TERMINATOR.next = PREV_TERMINATOR; |
183 |
NEXT_TERMINATOR = new Node<Object>(null); |
184 |
NEXT_TERMINATOR.prev = NEXT_TERMINATOR; |
185 |
} |
186 |
|
187 |
@SuppressWarnings("unchecked") |
188 |
Node<E> prevTerminator() { |
189 |
return (Node<E>) PREV_TERMINATOR; |
190 |
} |
191 |
|
192 |
@SuppressWarnings("unchecked") |
193 |
Node<E> nextTerminator() { |
194 |
return (Node<E>) NEXT_TERMINATOR; |
195 |
} |
196 |
|
197 |
/** |
198 |
* A node from which the last node on list (that is, the unique |
199 |
* node with node.next == null) can be reached in O(1) time. |
200 |
* Invariants: |
201 |
* - the last node is always O(1) reachable from tail via next links |
202 |
* - all live nodes are reachable from the last node via pred() |
203 |
* - tail != null |
204 |
* Non-invariants: |
205 |
* - tail.item may or may not be null |
206 |
* - tail may not be reachable from the first or last node, or from head |
207 |
*/ |
208 |
private transient volatile Node<E> tail = head; |
209 |
|
210 |
static final class Node<E> { |
211 |
volatile Node<E> prev; |
212 |
volatile E item; |
213 |
volatile Node<E> next; |
214 |
|
215 |
Node(E item) { |
216 |
// Piggyback on imminent casNext() or casPrev() |
217 |
lazySetItem(item); |
218 |
} |
219 |
|
220 |
boolean casItem(E cmp, E val) { |
221 |
return UNSAFE.compareAndSwapObject(this, itemOffset, cmp, val); |
222 |
} |
223 |
|
224 |
void lazySetItem(E val) { |
225 |
UNSAFE.putOrderedObject(this, itemOffset, val); |
226 |
} |
227 |
|
228 |
void lazySetNext(Node<E> val) { |
229 |
UNSAFE.putOrderedObject(this, nextOffset, val); |
230 |
} |
231 |
|
232 |
boolean casNext(Node<E> cmp, Node<E> val) { |
233 |
return UNSAFE.compareAndSwapObject(this, nextOffset, cmp, val); |
234 |
} |
235 |
|
236 |
void lazySetPrev(Node<E> val) { |
237 |
UNSAFE.putOrderedObject(this, prevOffset, val); |
238 |
} |
239 |
|
240 |
boolean casPrev(Node<E> cmp, Node<E> val) { |
241 |
return UNSAFE.compareAndSwapObject(this, prevOffset, cmp, val); |
242 |
} |
243 |
|
244 |
// Unsafe mechanics |
245 |
|
246 |
private static final sun.misc.Unsafe UNSAFE = |
247 |
sun.misc.Unsafe.getUnsafe(); |
248 |
private static final long prevOffset = |
249 |
objectFieldOffset(UNSAFE, "prev", Node.class); |
250 |
private static final long itemOffset = |
251 |
objectFieldOffset(UNSAFE, "item", Node.class); |
252 |
private static final long nextOffset = |
253 |
objectFieldOffset(UNSAFE, "next", Node.class); |
254 |
} |
255 |
|
256 |
/** |
257 |
* Links e as first element. |
258 |
*/ |
259 |
private void linkFirst(E e) { |
260 |
checkNotNull(e); |
261 |
final Node<E> newNode = new Node<E>(e); |
262 |
|
263 |
retry: |
264 |
for (;;) { |
265 |
for (Node<E> h = head, p = h;;) { |
266 |
Node<E> q = p.prev; |
267 |
if (q == null) { |
268 |
if (p.next == p) |
269 |
continue retry; |
270 |
newNode.lazySetNext(p); // CAS piggyback |
271 |
if (p.casPrev(null, newNode)) { |
272 |
if (p != h) // hop two nodes at a time |
273 |
casHead(h, newNode); |
274 |
return; |
275 |
} else { |
276 |
p = p.prev; // lost CAS race to another thread |
277 |
} |
278 |
} |
279 |
else if (p == q) |
280 |
continue retry; |
281 |
else |
282 |
p = q; |
283 |
} |
284 |
} |
285 |
} |
286 |
|
287 |
/** |
288 |
* Links e as last element. |
289 |
*/ |
290 |
private void linkLast(E e) { |
291 |
checkNotNull(e); |
292 |
final Node<E> newNode = new Node<E>(e); |
293 |
|
294 |
retry: |
295 |
for (;;) { |
296 |
for (Node<E> t = tail, p = t;;) { |
297 |
Node<E> q = p.next; |
298 |
if (q == null) { |
299 |
if (p.prev == p) |
300 |
continue retry; |
301 |
newNode.lazySetPrev(p); // CAS piggyback |
302 |
if (p.casNext(null, newNode)) { |
303 |
if (p != t) // hop two nodes at a time |
304 |
casTail(t, newNode); |
305 |
return; |
306 |
} else { |
307 |
p = p.next; // lost CAS race to another thread |
308 |
} |
309 |
} |
310 |
else if (p == q) |
311 |
continue retry; |
312 |
else |
313 |
p = q; |
314 |
} |
315 |
} |
316 |
} |
317 |
|
318 |
// TODO: Is there a better cheap way of performing some cleanup |
319 |
// operation "occasionally"? |
320 |
static class Count { |
321 |
int count = 0; |
322 |
} |
323 |
private final static ThreadLocal<Count> tlc = |
324 |
new ThreadLocal<Count>() { |
325 |
protected Count initialValue() { return new Count(); } |
326 |
}; |
327 |
private static boolean shouldGCUnlinkOccasionally() { |
328 |
return (tlc.get().count++ & 0x3) == 0; |
329 |
} |
330 |
|
331 |
private final static int HOPS = 2; |
332 |
|
333 |
/** |
334 |
* Unlinks non-null node x. |
335 |
*/ |
336 |
void unlink(Node<E> x) { |
337 |
assert x != null; |
338 |
assert x.item == null; |
339 |
assert x != PREV_TERMINATOR; |
340 |
assert x != NEXT_TERMINATOR; |
341 |
|
342 |
final Node<E> prev = x.prev; |
343 |
final Node<E> next = x.next; |
344 |
if (prev == null) { |
345 |
unlinkFirst(x, next); |
346 |
} else if (next == null) { |
347 |
unlinkLast(x, prev); |
348 |
} else { |
349 |
// Unlink interior node. |
350 |
// |
351 |
// This is the common case, since a series of polls at the |
352 |
// same end will be "interior" removes, except perhaps for |
353 |
// the first one, since end nodes cannot be physically removed. |
354 |
// |
355 |
// At any time, all active nodes are mutually reachable by |
356 |
// following a sequence of either next or prev pointers. |
357 |
// |
358 |
// Our strategy is to find the unique active predecessor |
359 |
// and successor of x. Try to fix up their links so that |
360 |
// they point to each other, leaving x unreachable from |
361 |
// active nodes. If successful, and if x has no live |
362 |
// predecessor/successor, we additionally try to leave |
363 |
// active nodes unreachable from x, by rechecking that |
364 |
// the status of predecessor and successor are unchanged |
365 |
// and ensuring that x is not reachable from tail/head, |
366 |
// before setting x's prev/next links to their logical |
367 |
// approximate replacements, self/TERMINATOR. |
368 |
Node<E> activePred, activeSucc; |
369 |
boolean isFirst, isLast; |
370 |
int hops = 1; |
371 |
|
372 |
// Find active predecessor |
373 |
for (Node<E> p = prev;; ++hops) { |
374 |
if (p.item != null) { |
375 |
activePred = p; |
376 |
isFirst = false; |
377 |
break; |
378 |
} |
379 |
Node<E> q = p.prev; |
380 |
if (q == null) { |
381 |
if (p == p.next) |
382 |
return; |
383 |
activePred = p; |
384 |
isFirst = true; |
385 |
break; |
386 |
} |
387 |
else if (p == q) |
388 |
return; |
389 |
else |
390 |
p = q; |
391 |
} |
392 |
|
393 |
// Find active successor |
394 |
for (Node<E> p = next;; ++hops) { |
395 |
if (p.item != null) { |
396 |
activeSucc = p; |
397 |
isLast = false; |
398 |
break; |
399 |
} |
400 |
Node<E> q = p.next; |
401 |
if (q == null) { |
402 |
if (p == p.prev) |
403 |
return; |
404 |
activeSucc = p; |
405 |
isLast = true; |
406 |
break; |
407 |
} |
408 |
else if (p == q) |
409 |
return; |
410 |
else |
411 |
p = q; |
412 |
} |
413 |
|
414 |
// TODO: better HOP heuristics |
415 |
if (hops < HOPS |
416 |
// always squeeze out interior deleted nodes |
417 |
&& (isFirst | isLast)) |
418 |
return; |
419 |
|
420 |
// Squeeze out deleted nodes between activePred and |
421 |
// activeSucc, including x. |
422 |
skipDeletedSuccessors(activePred); |
423 |
skipDeletedPredecessors(activeSucc); |
424 |
|
425 |
// Try to gc-unlink, if possible |
426 |
if ((isFirst | isLast) && |
427 |
//shouldGCUnlinkOccasionally() && |
428 |
|
429 |
// Recheck expected state of predecessor and successor |
430 |
(activePred.next == activeSucc) && |
431 |
(activeSucc.prev == activePred) && |
432 |
(isFirst ? activePred.prev == null : activePred.item != null) && |
433 |
(isLast ? activeSucc.next == null : activeSucc.item != null)) { |
434 |
|
435 |
// Ensure x is not reachable from head or tail |
436 |
updateHead(); |
437 |
updateTail(); |
438 |
x.lazySetPrev(isFirst ? prevTerminator() : x); |
439 |
x.lazySetNext(isLast ? nextTerminator() : x); |
440 |
} |
441 |
} |
442 |
} |
443 |
|
444 |
/** |
445 |
* Unlinks non-null first node. |
446 |
*/ |
447 |
private void unlinkFirst(Node<E> first, Node<E> next) { |
448 |
assert first != null && next != null && first.item == null; |
449 |
Node<E> o = null, p = next; |
450 |
for (int hops = 0;; ++hops) { |
451 |
Node<E> q; |
452 |
if (p.item != null || (q = p.next) == null) { |
453 |
if (hops >= HOPS) { |
454 |
if (p == p.prev) |
455 |
return; |
456 |
if (first.casNext(next, p)) { |
457 |
skipDeletedPredecessors(p); |
458 |
if (//shouldGCUnlinkOccasionally() && |
459 |
first.prev == null && |
460 |
(p.next == null || p.item != null) && |
461 |
p.prev == first) { |
462 |
|
463 |
updateHead(); |
464 |
updateTail(); |
465 |
o.lazySetNext(o); |
466 |
o.lazySetPrev(prevTerminator()); |
467 |
} |
468 |
} |
469 |
} |
470 |
return; |
471 |
} |
472 |
else if (p == q) |
473 |
return; |
474 |
else { |
475 |
o = p; |
476 |
p = q; |
477 |
} |
478 |
} |
479 |
} |
480 |
|
481 |
/** |
482 |
* Unlinks non-null last node. |
483 |
*/ |
484 |
private void unlinkLast(Node<E> last, Node<E> prev) { |
485 |
assert last != null && prev != null && last.item == null; |
486 |
Node<E> o = null, p = prev; |
487 |
for (int hops = 0;; ++hops) { |
488 |
Node<E> q; |
489 |
if (p.item != null || (q = p.prev) == null) { |
490 |
if (hops >= HOPS) { |
491 |
if (p == p.next) |
492 |
return; |
493 |
if (last.casPrev(prev, p)) { |
494 |
skipDeletedSuccessors(p); |
495 |
if (//shouldGCUnlinkOccasionally() && |
496 |
last.next == null && |
497 |
(p.prev == null || p.item != null) && |
498 |
p.next == last) { |
499 |
|
500 |
updateHead(); |
501 |
updateTail(); |
502 |
o.lazySetPrev(o); |
503 |
o.lazySetNext(nextTerminator()); |
504 |
} |
505 |
} |
506 |
} |
507 |
return; |
508 |
} |
509 |
else if (p == q) |
510 |
return; |
511 |
else { |
512 |
o = p; |
513 |
p = q; |
514 |
} |
515 |
} |
516 |
} |
517 |
|
518 |
private final void updateHead() { |
519 |
first(); |
520 |
} |
521 |
|
522 |
private final void updateTail() { |
523 |
last(); |
524 |
} |
525 |
|
526 |
private void skipDeletedPredecessors(Node<E> x) { |
527 |
whileActive: |
528 |
do { |
529 |
Node<E> prev = x.prev; |
530 |
assert prev != null; |
531 |
assert x != NEXT_TERMINATOR; |
532 |
assert x != PREV_TERMINATOR; |
533 |
Node<E> p = prev; |
534 |
findActive: |
535 |
for (;;) { |
536 |
if (p.item != null) |
537 |
break findActive; |
538 |
Node<E> q = p.prev; |
539 |
if (q == null) { |
540 |
if (p.next == p) |
541 |
continue whileActive; |
542 |
break findActive; |
543 |
} |
544 |
else if (p == q) |
545 |
continue whileActive; |
546 |
else |
547 |
p = q; |
548 |
} |
549 |
|
550 |
// found active CAS target |
551 |
if (prev == p || x.casPrev(prev, p)) |
552 |
return; |
553 |
|
554 |
} while (x.item != null || x.next == null); |
555 |
} |
556 |
|
557 |
private void skipDeletedSuccessors(Node<E> x) { |
558 |
whileActive: |
559 |
do { |
560 |
Node<E> next = x.next; |
561 |
assert next != null; |
562 |
assert x != NEXT_TERMINATOR; |
563 |
assert x != PREV_TERMINATOR; |
564 |
Node<E> p = next; |
565 |
findActive: |
566 |
for (;;) { |
567 |
if (p.item != null) |
568 |
break findActive; |
569 |
Node<E> q = p.next; |
570 |
if (q == null) { |
571 |
if (p.prev == p) |
572 |
continue whileActive; |
573 |
break findActive; |
574 |
} |
575 |
else if (p == q) |
576 |
continue whileActive; |
577 |
else |
578 |
p = q; |
579 |
} |
580 |
|
581 |
// found active CAS target |
582 |
if (next == p || x.casNext(next, p)) |
583 |
return; |
584 |
|
585 |
} while (x.item != null || x.prev == null); |
586 |
} |
587 |
|
588 |
/** |
589 |
* Returns the successor of p, or the first node if p.next has been |
590 |
* linked to self, which will only be true if traversing with a |
591 |
* stale pointer that is now off the list. |
592 |
*/ |
593 |
final Node<E> succ(Node<E> p) { |
594 |
// TODO: should we skip deleted nodes here? |
595 |
Node<E> q = p.next; |
596 |
return (p == q) ? first() : q; |
597 |
} |
598 |
|
599 |
/** |
600 |
* Returns the predecessor of p, or the last node if p.prev has been |
601 |
* linked to self, which will only be true if traversing with a |
602 |
* stale pointer that is now off the list. |
603 |
*/ |
604 |
final Node<E> pred(Node<E> p) { |
605 |
Node<E> q = p.prev; |
606 |
return (p == q) ? last() : q; |
607 |
} |
608 |
|
609 |
/** |
610 |
* Returns the first node, the unique node which has a null prev link. |
611 |
* The returned node may or may not be logically deleted. |
612 |
* Guarantees that head is set to the returned node. |
613 |
*/ |
614 |
Node<E> first() { |
615 |
retry: |
616 |
for (;;) { |
617 |
for (Node<E> h = head, p = h;;) { |
618 |
Node<E> q = p.prev; |
619 |
if (q == null) { |
620 |
if (p == h |
621 |
// It is possible that p is PREV_TERMINATOR, |
622 |
// but if so, the CAS will fail. |
623 |
|| casHead(h, p)) |
624 |
return p; |
625 |
else |
626 |
continue retry; |
627 |
} else if (p == q) { |
628 |
continue retry; |
629 |
} else { |
630 |
p = q; |
631 |
} |
632 |
} |
633 |
} |
634 |
} |
635 |
|
636 |
/** |
637 |
* Returns the last node, the unique node which has a null next link. |
638 |
* The returned node may or may not be logically deleted. |
639 |
* Guarantees that tail is set to the returned node. |
640 |
*/ |
641 |
Node<E> last() { |
642 |
retry: |
643 |
for (;;) { |
644 |
for (Node<E> t = tail, p = t;;) { |
645 |
Node<E> q = p.next; |
646 |
if (q == null) { |
647 |
if (p == t |
648 |
// It is possible that p is NEXT_TERMINATOR, |
649 |
// but if so, the CAS will fail. |
650 |
|| casTail(t, p)) |
651 |
return p; |
652 |
else |
653 |
continue retry; |
654 |
} else if (p == q) { |
655 |
continue retry; |
656 |
} else { |
657 |
p = q; |
658 |
} |
659 |
} |
660 |
} |
661 |
} |
662 |
|
663 |
// Minor convenience utilities |
664 |
|
665 |
/** |
666 |
* Throws NullPointerException if argument is null. |
667 |
* |
668 |
* @param v the element |
669 |
*/ |
670 |
private static void checkNotNull(Object v) { |
671 |
if (v == null) |
672 |
throw new NullPointerException(); |
673 |
} |
674 |
|
675 |
/** |
676 |
* Returns element unless it is null, in which case throws |
677 |
* NoSuchElementException. |
678 |
* |
679 |
* @param v the element |
680 |
* @return the element |
681 |
*/ |
682 |
private E screenNullResult(E v) { |
683 |
if (v == null) |
684 |
throw new NoSuchElementException(); |
685 |
return v; |
686 |
} |
687 |
|
688 |
/** |
689 |
* Creates an array list and fills it with elements of this list. |
690 |
* Used by toArray. |
691 |
* |
692 |
* @return the arrayList |
693 |
*/ |
694 |
private ArrayList<E> toArrayList() { |
695 |
ArrayList<E> c = new ArrayList<E>(); |
696 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
697 |
E item = p.item; |
698 |
if (item != null) |
699 |
c.add(item); |
700 |
} |
701 |
return c; |
702 |
} |
703 |
|
704 |
// Fields and constructors |
705 |
|
706 |
private static final long serialVersionUID = 876323262645176354L; |
707 |
|
708 |
/** |
709 |
* Constructs an empty deque. |
710 |
*/ |
711 |
public ConcurrentLinkedDeque() {} |
712 |
|
713 |
/** |
714 |
* Constructs a deque initially containing the elements of |
715 |
* the given collection, added in traversal order of the |
716 |
* collection's iterator. |
717 |
* |
718 |
* @param c the collection of elements to initially contain |
719 |
* @throws NullPointerException if the specified collection or any |
720 |
* of its elements are null |
721 |
*/ |
722 |
public ConcurrentLinkedDeque(Collection<? extends E> c) { |
723 |
this(); |
724 |
addAll(c); |
725 |
} |
726 |
|
727 |
/** |
728 |
* Inserts the specified element at the front of this deque. |
729 |
* |
730 |
* @throws NullPointerException {@inheritDoc} |
731 |
*/ |
732 |
public void addFirst(E e) { |
733 |
linkFirst(e); |
734 |
} |
735 |
|
736 |
/** |
737 |
* Inserts the specified element at the end of this deque. |
738 |
* This is identical in function to the {@code add} method. |
739 |
* |
740 |
* @throws NullPointerException {@inheritDoc} |
741 |
*/ |
742 |
public void addLast(E e) { |
743 |
linkLast(e); |
744 |
} |
745 |
|
746 |
/** |
747 |
* Inserts the specified element at the front of this deque. |
748 |
* |
749 |
* @return {@code true} always |
750 |
* @throws NullPointerException {@inheritDoc} |
751 |
*/ |
752 |
public boolean offerFirst(E e) { |
753 |
linkFirst(e); |
754 |
return true; |
755 |
} |
756 |
|
757 |
/** |
758 |
* Inserts the specified element at the end of this deque. |
759 |
* |
760 |
* <p>This method is equivalent to {@link #add}. |
761 |
* |
762 |
* @return {@code true} always |
763 |
* @throws NullPointerException {@inheritDoc} |
764 |
*/ |
765 |
public boolean offerLast(E e) { |
766 |
linkLast(e); |
767 |
return true; |
768 |
} |
769 |
|
770 |
public E peekFirst() { |
771 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
772 |
E item = p.item; |
773 |
if (item != null) |
774 |
return item; |
775 |
} |
776 |
return null; |
777 |
} |
778 |
|
779 |
public E peekLast() { |
780 |
for (Node<E> p = last(); p != null; p = pred(p)) { |
781 |
E item = p.item; |
782 |
if (item != null) |
783 |
return item; |
784 |
} |
785 |
return null; |
786 |
} |
787 |
|
788 |
/** |
789 |
* @throws NoSuchElementException {@inheritDoc} |
790 |
*/ |
791 |
public E getFirst() { |
792 |
return screenNullResult(peekFirst()); |
793 |
} |
794 |
|
795 |
/** |
796 |
* @throws NoSuchElementException {@inheritDoc} |
797 |
*/ |
798 |
public E getLast() { |
799 |
return screenNullResult(peekLast()); |
800 |
} |
801 |
|
802 |
public E pollFirst() { |
803 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
804 |
E item = p.item; |
805 |
if (item != null && p.casItem(item, null)) { |
806 |
unlink(p); |
807 |
return item; |
808 |
} |
809 |
} |
810 |
return null; |
811 |
} |
812 |
|
813 |
public E pollLast() { |
814 |
for (Node<E> p = last(); p != null; p = pred(p)) { |
815 |
E item = p.item; |
816 |
if (item != null && p.casItem(item, null)) { |
817 |
unlink(p); |
818 |
return item; |
819 |
} |
820 |
} |
821 |
return null; |
822 |
} |
823 |
|
824 |
/** |
825 |
* @throws NoSuchElementException {@inheritDoc} |
826 |
*/ |
827 |
public E removeFirst() { |
828 |
return screenNullResult(pollFirst()); |
829 |
} |
830 |
|
831 |
/** |
832 |
* @throws NoSuchElementException {@inheritDoc} |
833 |
*/ |
834 |
public E removeLast() { |
835 |
return screenNullResult(pollLast()); |
836 |
} |
837 |
|
838 |
// *** Queue and stack methods *** |
839 |
|
840 |
/** |
841 |
* Inserts the specified element at the tail of this deque. |
842 |
* |
843 |
* @return {@code true} (as specified by {@link Queue#offer}) |
844 |
* @throws NullPointerException if the specified element is null |
845 |
*/ |
846 |
public boolean offer(E e) { |
847 |
return offerLast(e); |
848 |
} |
849 |
|
850 |
/** |
851 |
* Inserts the specified element at the tail of this deque. |
852 |
* |
853 |
* @return {@code true} (as specified by {@link Collection#add}) |
854 |
* @throws NullPointerException if the specified element is null |
855 |
*/ |
856 |
public boolean add(E e) { |
857 |
return offerLast(e); |
858 |
} |
859 |
|
860 |
public E poll() { return pollFirst(); } |
861 |
public E remove() { return removeFirst(); } |
862 |
public E peek() { return peekFirst(); } |
863 |
public E element() { return getFirst(); } |
864 |
public void push(E e) { addFirst(e); } |
865 |
public E pop() { return removeFirst(); } |
866 |
|
867 |
/** |
868 |
* Removes the first element {@code e} such that |
869 |
* {@code o.equals(e)}, if such an element exists in this deque. |
870 |
* If the deque does not contain the element, it is unchanged. |
871 |
* |
872 |
* @param o element to be removed from this deque, if present |
873 |
* @return {@code true} if the deque contained the specified element |
874 |
* @throws NullPointerException if the specified element is {@code null} |
875 |
*/ |
876 |
public boolean removeFirstOccurrence(Object o) { |
877 |
checkNotNull(o); |
878 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
879 |
E item = p.item; |
880 |
if (item != null && o.equals(item) && p.casItem(item, null)) { |
881 |
unlink(p); |
882 |
return true; |
883 |
} |
884 |
} |
885 |
return false; |
886 |
} |
887 |
|
888 |
/** |
889 |
* Removes the last element {@code e} such that |
890 |
* {@code o.equals(e)}, if such an element exists in this deque. |
891 |
* If the deque does not contain the element, it is unchanged. |
892 |
* |
893 |
* @param o element to be removed from this deque, if present |
894 |
* @return {@code true} if the deque contained the specified element |
895 |
* @throws NullPointerException if the specified element is {@code null} |
896 |
*/ |
897 |
public boolean removeLastOccurrence(Object o) { |
898 |
checkNotNull(o); |
899 |
for (Node<E> p = last(); p != null; p = pred(p)) { |
900 |
E item = p.item; |
901 |
if (item != null && o.equals(item) && p.casItem(item, null)) { |
902 |
unlink(p); |
903 |
return true; |
904 |
} |
905 |
} |
906 |
return false; |
907 |
} |
908 |
|
909 |
/** |
910 |
* Returns {@code true} if this deque contains at least one |
911 |
* element {@code e} such that {@code o.equals(e)}. |
912 |
* |
913 |
* @param o element whose presence in this deque is to be tested |
914 |
* @return {@code true} if this deque contains the specified element |
915 |
*/ |
916 |
public boolean contains(Object o) { |
917 |
if (o == null) return false; |
918 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
919 |
E item = p.item; |
920 |
if (item != null && o.equals(item)) |
921 |
return true; |
922 |
} |
923 |
return false; |
924 |
} |
925 |
|
926 |
/** |
927 |
* Returns {@code true} if this collection contains no elements. |
928 |
* |
929 |
* @return {@code true} if this collection contains no elements |
930 |
*/ |
931 |
public boolean isEmpty() { |
932 |
return peekFirst() == null; |
933 |
} |
934 |
|
935 |
/** |
936 |
* Returns the number of elements in this deque. If this deque |
937 |
* contains more than {@code Integer.MAX_VALUE} elements, it |
938 |
* returns {@code Integer.MAX_VALUE}. |
939 |
* |
940 |
* <p>Beware that, unlike in most collections, this method is |
941 |
* <em>NOT</em> a constant-time operation. Because of the |
942 |
* asynchronous nature of these deques, determining the current |
943 |
* number of elements requires traversing them all to count them. |
944 |
* Additionally, it is possible for the size to change during |
945 |
* execution of this method, in which case the returned result |
946 |
* will be inaccurate. Thus, this method is typically not very |
947 |
* useful in concurrent applications. |
948 |
* |
949 |
* @return the number of elements in this deque |
950 |
*/ |
951 |
public int size() { |
952 |
long count = 0; |
953 |
for (Node<E> p = first(); p != null; p = succ(p)) |
954 |
if (p.item != null) |
955 |
++count; |
956 |
return (count >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) count; |
957 |
} |
958 |
|
959 |
/** |
960 |
* Removes the first element {@code e} such that |
961 |
* {@code o.equals(e)}, if such an element exists in this deque. |
962 |
* If the deque does not contain the element, it is unchanged. |
963 |
* |
964 |
* @param o element to be removed from this deque, if present |
965 |
* @return {@code true} if the deque contained the specified element |
966 |
* @throws NullPointerException if the specified element is {@code null} |
967 |
*/ |
968 |
public boolean remove(Object o) { |
969 |
return removeFirstOccurrence(o); |
970 |
} |
971 |
|
972 |
/** |
973 |
* Appends all of the elements in the specified collection to the end of |
974 |
* this deque, in the order that they are returned by the specified |
975 |
* collection's iterator. The behavior of this operation is undefined if |
976 |
* the specified collection is modified while the operation is in |
977 |
* progress. (This implies that the behavior of this call is undefined if |
978 |
* the specified Collection is this deque, and this deque is nonempty.) |
979 |
* |
980 |
* @param c the elements to be inserted into this deque |
981 |
* @return {@code true} if this deque changed as a result of the call |
982 |
* @throws NullPointerException if {@code c} or any element within it |
983 |
* is {@code null} |
984 |
*/ |
985 |
public boolean addAll(Collection<? extends E> c) { |
986 |
Iterator<? extends E> it = c.iterator(); |
987 |
if (!it.hasNext()) |
988 |
return false; |
989 |
do { |
990 |
addLast(it.next()); |
991 |
} while (it.hasNext()); |
992 |
return true; |
993 |
} |
994 |
|
995 |
/** |
996 |
* Removes all of the elements from this deque. |
997 |
*/ |
998 |
public void clear() { |
999 |
while (pollFirst() != null) |
1000 |
; |
1001 |
} |
1002 |
|
1003 |
/** |
1004 |
* Returns an array containing all of the elements in this deque, in |
1005 |
* proper sequence (from first to last element). |
1006 |
* |
1007 |
* <p>The returned array will be "safe" in that no references to it are |
1008 |
* maintained by this deque. (In other words, this method must allocate |
1009 |
* a new array). The caller is thus free to modify the returned array. |
1010 |
* |
1011 |
* <p>This method acts as bridge between array-based and collection-based |
1012 |
* APIs. |
1013 |
* |
1014 |
* @return an array containing all of the elements in this deque |
1015 |
*/ |
1016 |
public Object[] toArray() { |
1017 |
return toArrayList().toArray(); |
1018 |
} |
1019 |
|
1020 |
/** |
1021 |
* Returns an array containing all of the elements in this deque, |
1022 |
* in proper sequence (from first to last element); the runtime |
1023 |
* type of the returned array is that of the specified array. If |
1024 |
* the deque fits in the specified array, it is returned therein. |
1025 |
* Otherwise, a new array is allocated with the runtime type of |
1026 |
* the specified array and the size of this deque. |
1027 |
* |
1028 |
* <p>If this deque fits in the specified array with room to spare |
1029 |
* (i.e., the array has more elements than this deque), the element in |
1030 |
* the array immediately following the end of the deque is set to |
1031 |
* {@code null}. |
1032 |
* |
1033 |
* <p>Like the {@link #toArray()} method, this method acts as bridge between |
1034 |
* array-based and collection-based APIs. Further, this method allows |
1035 |
* precise control over the runtime type of the output array, and may, |
1036 |
* under certain circumstances, be used to save allocation costs. |
1037 |
* |
1038 |
* <p>Suppose {@code x} is a deque known to contain only strings. |
1039 |
* The following code can be used to dump the deque into a newly |
1040 |
* allocated array of {@code String}: |
1041 |
* |
1042 |
* <pre> |
1043 |
* String[] y = x.toArray(new String[0]);</pre> |
1044 |
* |
1045 |
* Note that {@code toArray(new Object[0])} is identical in function to |
1046 |
* {@code toArray()}. |
1047 |
* |
1048 |
* @param a the array into which the elements of the deque are to |
1049 |
* be stored, if it is big enough; otherwise, a new array of the |
1050 |
* same runtime type is allocated for this purpose |
1051 |
* @return an array containing all of the elements in this deque |
1052 |
* @throws ArrayStoreException if the runtime type of the specified array |
1053 |
* is not a supertype of the runtime type of every element in |
1054 |
* this deque |
1055 |
* @throws NullPointerException if the specified array is null |
1056 |
*/ |
1057 |
public <T> T[] toArray(T[] a) { |
1058 |
return toArrayList().toArray(a); |
1059 |
} |
1060 |
|
1061 |
/** |
1062 |
* Returns an iterator over the elements in this deque in proper sequence. |
1063 |
* The elements will be returned in order from first (head) to last (tail). |
1064 |
* |
1065 |
* <p>The returned {@code Iterator} is a "weakly consistent" iterator that |
1066 |
* will never throw {@link java.util.ConcurrentModificationException |
1067 |
* ConcurrentModificationException}, |
1068 |
* and guarantees to traverse elements as they existed upon |
1069 |
* construction of the iterator, and may (but is not guaranteed to) |
1070 |
* reflect any modifications subsequent to construction. |
1071 |
* |
1072 |
* @return an iterator over the elements in this deque in proper sequence |
1073 |
*/ |
1074 |
public Iterator<E> iterator() { |
1075 |
return new Itr(); |
1076 |
} |
1077 |
|
1078 |
/** |
1079 |
* Returns an iterator over the elements in this deque in reverse |
1080 |
* sequential order. The elements will be returned in order from |
1081 |
* last (tail) to first (head). |
1082 |
* |
1083 |
* <p>The returned {@code Iterator} is a "weakly consistent" iterator that |
1084 |
* will never throw {@link java.util.ConcurrentModificationException |
1085 |
* ConcurrentModificationException}, |
1086 |
* and guarantees to traverse elements as they existed upon |
1087 |
* construction of the iterator, and may (but is not guaranteed to) |
1088 |
* reflect any modifications subsequent to construction. |
1089 |
*/ |
1090 |
public Iterator<E> descendingIterator() { |
1091 |
return new DescendingItr(); |
1092 |
} |
1093 |
|
1094 |
private abstract class AbstractItr implements Iterator<E> { |
1095 |
/** |
1096 |
* Next node to return item for. |
1097 |
*/ |
1098 |
private Node<E> nextNode; |
1099 |
|
1100 |
/** |
1101 |
* nextItem holds on to item fields because once we claim |
1102 |
* that an element exists in hasNext(), we must return it in |
1103 |
* the following next() call even if it was in the process of |
1104 |
* being removed when hasNext() was called. |
1105 |
*/ |
1106 |
private E nextItem; |
1107 |
|
1108 |
/** |
1109 |
* Node returned by most recent call to next. Needed by remove. |
1110 |
* Reset to null if this element is deleted by a call to remove. |
1111 |
*/ |
1112 |
private Node<E> lastRet; |
1113 |
|
1114 |
abstract Node<E> startNode(); |
1115 |
abstract Node<E> nextNode(Node<E> p); |
1116 |
|
1117 |
AbstractItr() { |
1118 |
advance(); |
1119 |
} |
1120 |
|
1121 |
/** |
1122 |
* Sets nextNode and nextItem to next valid node, or to null |
1123 |
* if no such. |
1124 |
*/ |
1125 |
private void advance() { |
1126 |
lastRet = nextNode; |
1127 |
|
1128 |
Node<E> p = (nextNode == null) ? startNode() : nextNode(nextNode); |
1129 |
for (;; p = nextNode(p)) { |
1130 |
if (p == null) { |
1131 |
// p might be active end or TERMINATOR node; both are OK |
1132 |
nextNode = null; |
1133 |
nextItem = null; |
1134 |
break; |
1135 |
} |
1136 |
E item = p.item; |
1137 |
if (item != null) { |
1138 |
nextNode = p; |
1139 |
nextItem = item; |
1140 |
break; |
1141 |
} |
1142 |
} |
1143 |
} |
1144 |
|
1145 |
public boolean hasNext() { |
1146 |
return nextItem != null; |
1147 |
} |
1148 |
|
1149 |
public E next() { |
1150 |
E item = nextItem; |
1151 |
if (item == null) throw new NoSuchElementException(); |
1152 |
advance(); |
1153 |
return item; |
1154 |
} |
1155 |
|
1156 |
public void remove() { |
1157 |
Node<E> l = lastRet; |
1158 |
if (l == null) throw new IllegalStateException(); |
1159 |
l.item = null; |
1160 |
unlink(l); |
1161 |
lastRet = null; |
1162 |
} |
1163 |
} |
1164 |
|
1165 |
/** Forward iterator */ |
1166 |
private class Itr extends AbstractItr { |
1167 |
Node<E> startNode() { return first(); } |
1168 |
Node<E> nextNode(Node<E> p) { return succ(p); } |
1169 |
} |
1170 |
|
1171 |
/** Descending iterator */ |
1172 |
private class DescendingItr extends AbstractItr { |
1173 |
Node<E> startNode() { return last(); } |
1174 |
Node<E> nextNode(Node<E> p) { return pred(p); } |
1175 |
} |
1176 |
|
1177 |
/** |
1178 |
* Save the state to a stream (that is, serialize it). |
1179 |
* |
1180 |
* @serialData All of the elements (each an {@code E}) in |
1181 |
* the proper order, followed by a null |
1182 |
* @param s the stream |
1183 |
*/ |
1184 |
private void writeObject(java.io.ObjectOutputStream s) |
1185 |
throws java.io.IOException { |
1186 |
|
1187 |
// Write out any hidden stuff |
1188 |
s.defaultWriteObject(); |
1189 |
|
1190 |
// Write out all elements in the proper order. |
1191 |
for (Node<E> p = first(); p != null; p = succ(p)) { |
1192 |
Object item = p.item; |
1193 |
if (item != null) |
1194 |
s.writeObject(item); |
1195 |
} |
1196 |
|
1197 |
// Use trailing null as sentinel |
1198 |
s.writeObject(null); |
1199 |
} |
1200 |
|
1201 |
/** |
1202 |
* Reconstitute the Queue instance from a stream (that is, |
1203 |
* deserialize it). |
1204 |
* @param s the stream |
1205 |
*/ |
1206 |
private void readObject(java.io.ObjectInputStream s) |
1207 |
throws java.io.IOException, ClassNotFoundException { |
1208 |
// Read in capacity, and any hidden stuff |
1209 |
s.defaultReadObject(); |
1210 |
tail = head = new Node<E>(null); |
1211 |
// Read in all elements and place in queue |
1212 |
for (;;) { |
1213 |
@SuppressWarnings("unchecked") |
1214 |
E item = (E)s.readObject(); |
1215 |
if (item == null) |
1216 |
break; |
1217 |
else |
1218 |
offer(item); |
1219 |
} |
1220 |
} |
1221 |
|
1222 |
// Unsafe mechanics |
1223 |
|
1224 |
private static final sun.misc.Unsafe UNSAFE = |
1225 |
sun.misc.Unsafe.getUnsafe(); |
1226 |
private static final long headOffset = |
1227 |
objectFieldOffset(UNSAFE, "head", ConcurrentLinkedDeque.class); |
1228 |
private static final long tailOffset = |
1229 |
objectFieldOffset(UNSAFE, "tail", ConcurrentLinkedDeque.class); |
1230 |
|
1231 |
private boolean casHead(Node<E> cmp, Node<E> val) { |
1232 |
return UNSAFE.compareAndSwapObject(this, headOffset, cmp, val); |
1233 |
} |
1234 |
|
1235 |
private boolean casTail(Node<E> cmp, Node<E> val) { |
1236 |
return UNSAFE.compareAndSwapObject(this, tailOffset, cmp, val); |
1237 |
} |
1238 |
|
1239 |
static long objectFieldOffset(sun.misc.Unsafe UNSAFE, |
1240 |
String field, Class<?> klazz) { |
1241 |
try { |
1242 |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(field)); |
1243 |
} catch (NoSuchFieldException e) { |
1244 |
// Convert Exception to corresponding Error |
1245 |
NoSuchFieldError error = new NoSuchFieldError(field); |
1246 |
error.initCause(e); |
1247 |
throw error; |
1248 |
} |
1249 |
} |
1250 |
} |