1 |
/* |
2 |
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
* Expert Group and released to the public domain, as explained at |
4 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
|
9 |
import java.util.AbstractQueue; |
10 |
import java.util.Collection; |
11 |
import java.util.Iterator; |
12 |
import java.util.NoSuchElementException; |
13 |
import java.util.Spliterator; |
14 |
import java.util.Spliterators; |
15 |
import java.util.concurrent.locks.Condition; |
16 |
import java.util.concurrent.locks.ReentrantLock; |
17 |
import java.util.function.Consumer; |
18 |
|
19 |
/** |
20 |
* An optionally-bounded {@linkplain BlockingDeque blocking deque} based on |
21 |
* linked nodes. |
22 |
* |
23 |
* <p>The optional capacity bound constructor argument serves as a |
24 |
* way to prevent excessive expansion. The capacity, if unspecified, |
25 |
* is equal to {@link Integer#MAX_VALUE}. Linked nodes are |
26 |
* dynamically created upon each insertion unless this would bring the |
27 |
* deque above capacity. |
28 |
* |
29 |
* <p>Most operations run in constant time (ignoring time spent |
30 |
* blocking). Exceptions include {@link #remove(Object) remove}, |
31 |
* {@link #removeFirstOccurrence removeFirstOccurrence}, {@link |
32 |
* #removeLastOccurrence removeLastOccurrence}, {@link #contains |
33 |
* contains}, {@link #iterator iterator.remove()}, and the bulk |
34 |
* operations, all of which run in linear time. |
35 |
* |
36 |
* <p>This class and its iterator implement all of the |
37 |
* <em>optional</em> methods of the {@link Collection} and {@link |
38 |
* Iterator} interfaces. |
39 |
* |
40 |
* <p>This class is a member of the |
41 |
* <a href="{@docRoot}/../technotes/guides/collections/index.html"> |
42 |
* Java Collections Framework</a>. |
43 |
* |
44 |
* @since 1.6 |
45 |
* @author Doug Lea |
46 |
* @param <E> the type of elements held in this deque |
47 |
*/ |
48 |
public class LinkedBlockingDeque<E> |
49 |
extends AbstractQueue<E> |
50 |
implements BlockingDeque<E>, java.io.Serializable { |
51 |
|
52 |
/* |
53 |
* Implemented as a simple doubly-linked list protected by a |
54 |
* single lock and using conditions to manage blocking. |
55 |
* |
56 |
* To implement weakly consistent iterators, it appears we need to |
57 |
* keep all Nodes GC-reachable from a predecessor dequeued Node. |
58 |
* That would cause two problems: |
59 |
* - allow a rogue Iterator to cause unbounded memory retention |
60 |
* - cause cross-generational linking of old Nodes to new Nodes if |
61 |
* a Node was tenured while live, which generational GCs have a |
62 |
* hard time dealing with, causing repeated major collections. |
63 |
* However, only non-deleted Nodes need to be reachable from |
64 |
* dequeued Nodes, and reachability does not necessarily have to |
65 |
* be of the kind understood by the GC. We use the trick of |
66 |
* linking a Node that has just been dequeued to itself. Such a |
67 |
* self-link implicitly means to jump to "first" (for next links) |
68 |
* or "last" (for prev links). |
69 |
*/ |
70 |
|
71 |
/* |
72 |
* We have "diamond" multiple interface/abstract class inheritance |
73 |
* here, and that introduces ambiguities. Often we want the |
74 |
* BlockingDeque javadoc combined with the AbstractQueue |
75 |
* implementation, so a lot of method specs are duplicated here. |
76 |
*/ |
77 |
|
78 |
private static final long serialVersionUID = -387911632671998426L; |
79 |
|
80 |
/** Doubly-linked list node class */ |
81 |
static final class Node<E> { |
82 |
/** |
83 |
* The item, or null if this node has been removed. |
84 |
*/ |
85 |
E item; |
86 |
|
87 |
/** |
88 |
* One of: |
89 |
* - the real predecessor Node |
90 |
* - this Node, meaning the predecessor is tail |
91 |
* - null, meaning there is no predecessor |
92 |
*/ |
93 |
Node<E> prev; |
94 |
|
95 |
/** |
96 |
* One of: |
97 |
* - the real successor Node |
98 |
* - this Node, meaning the successor is head |
99 |
* - null, meaning there is no successor |
100 |
*/ |
101 |
Node<E> next; |
102 |
|
103 |
Node(E x) { |
104 |
item = x; |
105 |
} |
106 |
} |
107 |
|
108 |
/** |
109 |
* Pointer to first node. |
110 |
* Invariant: (first == null && last == null) || |
111 |
* (first.prev == null && first.item != null) |
112 |
*/ |
113 |
transient Node<E> first; |
114 |
|
115 |
/** |
116 |
* Pointer to last node. |
117 |
* Invariant: (first == null && last == null) || |
118 |
* (last.next == null && last.item != null) |
119 |
*/ |
120 |
transient Node<E> last; |
121 |
|
122 |
/** Number of items in the deque */ |
123 |
private transient int count; |
124 |
|
125 |
/** Maximum number of items in the deque */ |
126 |
private final int capacity; |
127 |
|
128 |
/** Main lock guarding all access */ |
129 |
final ReentrantLock lock = new ReentrantLock(); |
130 |
|
131 |
/** Condition for waiting takes */ |
132 |
private final Condition notEmpty = lock.newCondition(); |
133 |
|
134 |
/** Condition for waiting puts */ |
135 |
private final Condition notFull = lock.newCondition(); |
136 |
|
137 |
/** |
138 |
* Creates a {@code LinkedBlockingDeque} with a capacity of |
139 |
* {@link Integer#MAX_VALUE}. |
140 |
*/ |
141 |
public LinkedBlockingDeque() { |
142 |
this(Integer.MAX_VALUE); |
143 |
} |
144 |
|
145 |
/** |
146 |
* Creates a {@code LinkedBlockingDeque} with the given (fixed) capacity. |
147 |
* |
148 |
* @param capacity the capacity of this deque |
149 |
* @throws IllegalArgumentException if {@code capacity} is less than 1 |
150 |
*/ |
151 |
public LinkedBlockingDeque(int capacity) { |
152 |
if (capacity <= 0) throw new IllegalArgumentException(); |
153 |
this.capacity = capacity; |
154 |
} |
155 |
|
156 |
/** |
157 |
* Creates a {@code LinkedBlockingDeque} with a capacity of |
158 |
* {@link Integer#MAX_VALUE}, initially containing the elements of |
159 |
* the given collection, added in traversal order of the |
160 |
* collection's iterator. |
161 |
* |
162 |
* @param c the collection of elements to initially contain |
163 |
* @throws NullPointerException if the specified collection or any |
164 |
* of its elements are null |
165 |
*/ |
166 |
public LinkedBlockingDeque(Collection<? extends E> c) { |
167 |
this(Integer.MAX_VALUE); |
168 |
final ReentrantLock lock = this.lock; |
169 |
lock.lock(); // Never contended, but necessary for visibility |
170 |
try { |
171 |
for (E e : c) { |
172 |
if (e == null) |
173 |
throw new NullPointerException(); |
174 |
if (!linkLast(new Node<E>(e))) |
175 |
throw new IllegalStateException("Deque full"); |
176 |
} |
177 |
} finally { |
178 |
// checkInvariants(); |
179 |
lock.unlock(); |
180 |
} |
181 |
} |
182 |
|
183 |
|
184 |
// Basic linking and unlinking operations, called only while holding lock |
185 |
|
186 |
/** |
187 |
* Links node as first element, or returns false if full. |
188 |
*/ |
189 |
private boolean linkFirst(Node<E> node) { |
190 |
// assert lock.isHeldByCurrentThread(); |
191 |
if (count >= capacity) |
192 |
return false; |
193 |
Node<E> f = first; |
194 |
node.next = f; |
195 |
first = node; |
196 |
if (last == null) |
197 |
last = node; |
198 |
else |
199 |
f.prev = node; |
200 |
++count; |
201 |
notEmpty.signal(); |
202 |
return true; |
203 |
} |
204 |
|
205 |
/** |
206 |
* Links node as last element, or returns false if full. |
207 |
*/ |
208 |
private boolean linkLast(Node<E> node) { |
209 |
// assert lock.isHeldByCurrentThread(); |
210 |
if (count >= capacity) |
211 |
return false; |
212 |
Node<E> l = last; |
213 |
node.prev = l; |
214 |
last = node; |
215 |
if (first == null) |
216 |
first = node; |
217 |
else |
218 |
l.next = node; |
219 |
++count; |
220 |
notEmpty.signal(); |
221 |
return true; |
222 |
} |
223 |
|
224 |
/** |
225 |
* Removes and returns first element, or null if empty. |
226 |
*/ |
227 |
private E unlinkFirst() { |
228 |
// assert lock.isHeldByCurrentThread(); |
229 |
Node<E> f = first; |
230 |
if (f == null) |
231 |
return null; |
232 |
Node<E> n = f.next; |
233 |
E item = f.item; |
234 |
f.item = null; |
235 |
f.next = f; // help GC |
236 |
first = n; |
237 |
if (n == null) |
238 |
last = null; |
239 |
else |
240 |
n.prev = null; |
241 |
--count; |
242 |
notFull.signal(); |
243 |
return item; |
244 |
} |
245 |
|
246 |
/** |
247 |
* Removes and returns last element, or null if empty. |
248 |
*/ |
249 |
private E unlinkLast() { |
250 |
// assert lock.isHeldByCurrentThread(); |
251 |
Node<E> l = last; |
252 |
if (l == null) |
253 |
return null; |
254 |
Node<E> p = l.prev; |
255 |
E item = l.item; |
256 |
l.item = null; |
257 |
l.prev = l; // help GC |
258 |
last = p; |
259 |
if (p == null) |
260 |
first = null; |
261 |
else |
262 |
p.next = null; |
263 |
--count; |
264 |
notFull.signal(); |
265 |
return item; |
266 |
} |
267 |
|
268 |
/** |
269 |
* Unlinks x. |
270 |
*/ |
271 |
void unlink(Node<E> x) { |
272 |
// assert lock.isHeldByCurrentThread(); |
273 |
Node<E> p = x.prev; |
274 |
Node<E> n = x.next; |
275 |
if (p == null) { |
276 |
unlinkFirst(); |
277 |
} else if (n == null) { |
278 |
unlinkLast(); |
279 |
} else { |
280 |
p.next = n; |
281 |
n.prev = p; |
282 |
x.item = null; |
283 |
// Don't mess with x's links. They may still be in use by |
284 |
// an iterator. |
285 |
--count; |
286 |
notFull.signal(); |
287 |
} |
288 |
} |
289 |
|
290 |
// BlockingDeque methods |
291 |
|
292 |
/** |
293 |
* @throws IllegalStateException if this deque is full |
294 |
* @throws NullPointerException {@inheritDoc} |
295 |
*/ |
296 |
public void addFirst(E e) { |
297 |
if (!offerFirst(e)) |
298 |
throw new IllegalStateException("Deque full"); |
299 |
} |
300 |
|
301 |
/** |
302 |
* @throws IllegalStateException if this deque is full |
303 |
* @throws NullPointerException {@inheritDoc} |
304 |
*/ |
305 |
public void addLast(E e) { |
306 |
if (!offerLast(e)) |
307 |
throw new IllegalStateException("Deque full"); |
308 |
} |
309 |
|
310 |
/** |
311 |
* @throws NullPointerException {@inheritDoc} |
312 |
*/ |
313 |
public boolean offerFirst(E e) { |
314 |
if (e == null) throw new NullPointerException(); |
315 |
Node<E> node = new Node<E>(e); |
316 |
final ReentrantLock lock = this.lock; |
317 |
lock.lock(); |
318 |
try { |
319 |
return linkFirst(node); |
320 |
} finally { |
321 |
// checkInvariants(); |
322 |
lock.unlock(); |
323 |
} |
324 |
} |
325 |
|
326 |
/** |
327 |
* @throws NullPointerException {@inheritDoc} |
328 |
*/ |
329 |
public boolean offerLast(E e) { |
330 |
if (e == null) throw new NullPointerException(); |
331 |
Node<E> node = new Node<E>(e); |
332 |
final ReentrantLock lock = this.lock; |
333 |
lock.lock(); |
334 |
try { |
335 |
return linkLast(node); |
336 |
} finally { |
337 |
// checkInvariants(); |
338 |
lock.unlock(); |
339 |
} |
340 |
} |
341 |
|
342 |
/** |
343 |
* @throws NullPointerException {@inheritDoc} |
344 |
* @throws InterruptedException {@inheritDoc} |
345 |
*/ |
346 |
public void putFirst(E e) throws InterruptedException { |
347 |
if (e == null) throw new NullPointerException(); |
348 |
Node<E> node = new Node<E>(e); |
349 |
final ReentrantLock lock = this.lock; |
350 |
lock.lock(); |
351 |
try { |
352 |
while (!linkFirst(node)) |
353 |
notFull.await(); |
354 |
} finally { |
355 |
// checkInvariants(); |
356 |
lock.unlock(); |
357 |
} |
358 |
} |
359 |
|
360 |
/** |
361 |
* @throws NullPointerException {@inheritDoc} |
362 |
* @throws InterruptedException {@inheritDoc} |
363 |
*/ |
364 |
public void putLast(E e) throws InterruptedException { |
365 |
if (e == null) throw new NullPointerException(); |
366 |
Node<E> node = new Node<E>(e); |
367 |
final ReentrantLock lock = this.lock; |
368 |
lock.lock(); |
369 |
try { |
370 |
while (!linkLast(node)) |
371 |
notFull.await(); |
372 |
} finally { |
373 |
// checkInvariants(); |
374 |
lock.unlock(); |
375 |
} |
376 |
} |
377 |
|
378 |
/** |
379 |
* @throws NullPointerException {@inheritDoc} |
380 |
* @throws InterruptedException {@inheritDoc} |
381 |
*/ |
382 |
public boolean offerFirst(E e, long timeout, TimeUnit unit) |
383 |
throws InterruptedException { |
384 |
if (e == null) throw new NullPointerException(); |
385 |
Node<E> node = new Node<E>(e); |
386 |
long nanos = unit.toNanos(timeout); |
387 |
final ReentrantLock lock = this.lock; |
388 |
lock.lockInterruptibly(); |
389 |
try { |
390 |
while (!linkFirst(node)) { |
391 |
if (nanos <= 0L) |
392 |
return false; |
393 |
nanos = notFull.awaitNanos(nanos); |
394 |
} |
395 |
return true; |
396 |
} finally { |
397 |
// checkInvariants(); |
398 |
lock.unlock(); |
399 |
} |
400 |
} |
401 |
|
402 |
/** |
403 |
* @throws NullPointerException {@inheritDoc} |
404 |
* @throws InterruptedException {@inheritDoc} |
405 |
*/ |
406 |
public boolean offerLast(E e, long timeout, TimeUnit unit) |
407 |
throws InterruptedException { |
408 |
if (e == null) throw new NullPointerException(); |
409 |
Node<E> node = new Node<E>(e); |
410 |
long nanos = unit.toNanos(timeout); |
411 |
final ReentrantLock lock = this.lock; |
412 |
lock.lockInterruptibly(); |
413 |
try { |
414 |
while (!linkLast(node)) { |
415 |
if (nanos <= 0L) |
416 |
return false; |
417 |
nanos = notFull.awaitNanos(nanos); |
418 |
} |
419 |
return true; |
420 |
} finally { |
421 |
// checkInvariants(); |
422 |
lock.unlock(); |
423 |
} |
424 |
} |
425 |
|
426 |
/** |
427 |
* @throws NoSuchElementException {@inheritDoc} |
428 |
*/ |
429 |
public E removeFirst() { |
430 |
E x = pollFirst(); |
431 |
if (x == null) throw new NoSuchElementException(); |
432 |
return x; |
433 |
} |
434 |
|
435 |
/** |
436 |
* @throws NoSuchElementException {@inheritDoc} |
437 |
*/ |
438 |
public E removeLast() { |
439 |
E x = pollLast(); |
440 |
if (x == null) throw new NoSuchElementException(); |
441 |
return x; |
442 |
} |
443 |
|
444 |
public E pollFirst() { |
445 |
final ReentrantLock lock = this.lock; |
446 |
lock.lock(); |
447 |
try { |
448 |
return unlinkFirst(); |
449 |
} finally { |
450 |
// checkInvariants(); |
451 |
lock.unlock(); |
452 |
} |
453 |
} |
454 |
|
455 |
public E pollLast() { |
456 |
final ReentrantLock lock = this.lock; |
457 |
lock.lock(); |
458 |
try { |
459 |
return unlinkLast(); |
460 |
} finally { |
461 |
// checkInvariants(); |
462 |
lock.unlock(); |
463 |
} |
464 |
} |
465 |
|
466 |
public E takeFirst() throws InterruptedException { |
467 |
final ReentrantLock lock = this.lock; |
468 |
lock.lock(); |
469 |
try { |
470 |
E x; |
471 |
while ( (x = unlinkFirst()) == null) |
472 |
notEmpty.await(); |
473 |
return x; |
474 |
} finally { |
475 |
// checkInvariants(); |
476 |
lock.unlock(); |
477 |
} |
478 |
} |
479 |
|
480 |
public E takeLast() throws InterruptedException { |
481 |
final ReentrantLock lock = this.lock; |
482 |
lock.lock(); |
483 |
try { |
484 |
E x; |
485 |
while ( (x = unlinkLast()) == null) |
486 |
notEmpty.await(); |
487 |
return x; |
488 |
} finally { |
489 |
// checkInvariants(); |
490 |
lock.unlock(); |
491 |
} |
492 |
} |
493 |
|
494 |
public E pollFirst(long timeout, TimeUnit unit) |
495 |
throws InterruptedException { |
496 |
long nanos = unit.toNanos(timeout); |
497 |
final ReentrantLock lock = this.lock; |
498 |
lock.lockInterruptibly(); |
499 |
try { |
500 |
E x; |
501 |
while ( (x = unlinkFirst()) == null) { |
502 |
if (nanos <= 0L) |
503 |
return null; |
504 |
nanos = notEmpty.awaitNanos(nanos); |
505 |
} |
506 |
return x; |
507 |
} finally { |
508 |
// checkInvariants(); |
509 |
lock.unlock(); |
510 |
} |
511 |
} |
512 |
|
513 |
public E pollLast(long timeout, TimeUnit unit) |
514 |
throws InterruptedException { |
515 |
long nanos = unit.toNanos(timeout); |
516 |
final ReentrantLock lock = this.lock; |
517 |
lock.lockInterruptibly(); |
518 |
try { |
519 |
E x; |
520 |
while ( (x = unlinkLast()) == null) { |
521 |
if (nanos <= 0L) |
522 |
return null; |
523 |
nanos = notEmpty.awaitNanos(nanos); |
524 |
} |
525 |
return x; |
526 |
} finally { |
527 |
// checkInvariants(); |
528 |
lock.unlock(); |
529 |
} |
530 |
} |
531 |
|
532 |
/** |
533 |
* @throws NoSuchElementException {@inheritDoc} |
534 |
*/ |
535 |
public E getFirst() { |
536 |
E x = peekFirst(); |
537 |
if (x == null) throw new NoSuchElementException(); |
538 |
return x; |
539 |
} |
540 |
|
541 |
/** |
542 |
* @throws NoSuchElementException {@inheritDoc} |
543 |
*/ |
544 |
public E getLast() { |
545 |
E x = peekLast(); |
546 |
if (x == null) throw new NoSuchElementException(); |
547 |
return x; |
548 |
} |
549 |
|
550 |
public E peekFirst() { |
551 |
final ReentrantLock lock = this.lock; |
552 |
lock.lock(); |
553 |
try { |
554 |
return (first == null) ? null : first.item; |
555 |
} finally { |
556 |
// checkInvariants(); |
557 |
lock.unlock(); |
558 |
} |
559 |
} |
560 |
|
561 |
public E peekLast() { |
562 |
final ReentrantLock lock = this.lock; |
563 |
lock.lock(); |
564 |
try { |
565 |
return (last == null) ? null : last.item; |
566 |
} finally { |
567 |
// checkInvariants(); |
568 |
lock.unlock(); |
569 |
} |
570 |
} |
571 |
|
572 |
public boolean removeFirstOccurrence(Object o) { |
573 |
if (o == null) return false; |
574 |
final ReentrantLock lock = this.lock; |
575 |
lock.lock(); |
576 |
try { |
577 |
for (Node<E> p = first; p != null; p = p.next) { |
578 |
if (o.equals(p.item)) { |
579 |
unlink(p); |
580 |
return true; |
581 |
} |
582 |
} |
583 |
return false; |
584 |
} finally { |
585 |
// checkInvariants(); |
586 |
lock.unlock(); |
587 |
} |
588 |
} |
589 |
|
590 |
public boolean removeLastOccurrence(Object o) { |
591 |
if (o == null) return false; |
592 |
final ReentrantLock lock = this.lock; |
593 |
lock.lock(); |
594 |
try { |
595 |
for (Node<E> p = last; p != null; p = p.prev) { |
596 |
if (o.equals(p.item)) { |
597 |
unlink(p); |
598 |
return true; |
599 |
} |
600 |
} |
601 |
return false; |
602 |
} finally { |
603 |
// checkInvariants(); |
604 |
lock.unlock(); |
605 |
} |
606 |
} |
607 |
|
608 |
// BlockingQueue methods |
609 |
|
610 |
/** |
611 |
* Inserts the specified element at the end of this deque unless it would |
612 |
* violate capacity restrictions. When using a capacity-restricted deque, |
613 |
* it is generally preferable to use method {@link #offer(Object) offer}. |
614 |
* |
615 |
* <p>This method is equivalent to {@link #addLast}. |
616 |
* |
617 |
* @throws IllegalStateException if this deque is full |
618 |
* @throws NullPointerException if the specified element is null |
619 |
*/ |
620 |
public boolean add(E e) { |
621 |
addLast(e); |
622 |
return true; |
623 |
} |
624 |
|
625 |
/** |
626 |
* @throws NullPointerException if the specified element is null |
627 |
*/ |
628 |
public boolean offer(E e) { |
629 |
return offerLast(e); |
630 |
} |
631 |
|
632 |
/** |
633 |
* @throws NullPointerException {@inheritDoc} |
634 |
* @throws InterruptedException {@inheritDoc} |
635 |
*/ |
636 |
public void put(E e) throws InterruptedException { |
637 |
putLast(e); |
638 |
} |
639 |
|
640 |
/** |
641 |
* @throws NullPointerException {@inheritDoc} |
642 |
* @throws InterruptedException {@inheritDoc} |
643 |
*/ |
644 |
public boolean offer(E e, long timeout, TimeUnit unit) |
645 |
throws InterruptedException { |
646 |
return offerLast(e, timeout, unit); |
647 |
} |
648 |
|
649 |
/** |
650 |
* Retrieves and removes the head of the queue represented by this deque. |
651 |
* This method differs from {@link #poll poll} only in that it throws an |
652 |
* exception if this deque is empty. |
653 |
* |
654 |
* <p>This method is equivalent to {@link #removeFirst() removeFirst}. |
655 |
* |
656 |
* @return the head of the queue represented by this deque |
657 |
* @throws NoSuchElementException if this deque is empty |
658 |
*/ |
659 |
public E remove() { |
660 |
return removeFirst(); |
661 |
} |
662 |
|
663 |
public E poll() { |
664 |
return pollFirst(); |
665 |
} |
666 |
|
667 |
public E take() throws InterruptedException { |
668 |
return takeFirst(); |
669 |
} |
670 |
|
671 |
public E poll(long timeout, TimeUnit unit) throws InterruptedException { |
672 |
return pollFirst(timeout, unit); |
673 |
} |
674 |
|
675 |
/** |
676 |
* Retrieves, but does not remove, the head of the queue represented by |
677 |
* this deque. This method differs from {@link #peek peek} only in that |
678 |
* it throws an exception if this deque is empty. |
679 |
* |
680 |
* <p>This method is equivalent to {@link #getFirst() getFirst}. |
681 |
* |
682 |
* @return the head of the queue represented by this deque |
683 |
* @throws NoSuchElementException if this deque is empty |
684 |
*/ |
685 |
public E element() { |
686 |
return getFirst(); |
687 |
} |
688 |
|
689 |
public E peek() { |
690 |
return peekFirst(); |
691 |
} |
692 |
|
693 |
/** |
694 |
* Returns the number of additional elements that this deque can ideally |
695 |
* (in the absence of memory or resource constraints) accept without |
696 |
* blocking. This is always equal to the initial capacity of this deque |
697 |
* less the current {@code size} of this deque. |
698 |
* |
699 |
* <p>Note that you <em>cannot</em> always tell if an attempt to insert |
700 |
* an element will succeed by inspecting {@code remainingCapacity} |
701 |
* because it may be the case that another thread is about to |
702 |
* insert or remove an element. |
703 |
*/ |
704 |
public int remainingCapacity() { |
705 |
final ReentrantLock lock = this.lock; |
706 |
lock.lock(); |
707 |
try { |
708 |
return capacity - count; |
709 |
} finally { |
710 |
// checkInvariants(); |
711 |
lock.unlock(); |
712 |
} |
713 |
} |
714 |
|
715 |
/** |
716 |
* @throws UnsupportedOperationException {@inheritDoc} |
717 |
* @throws ClassCastException {@inheritDoc} |
718 |
* @throws NullPointerException {@inheritDoc} |
719 |
* @throws IllegalArgumentException {@inheritDoc} |
720 |
*/ |
721 |
public int drainTo(Collection<? super E> c) { |
722 |
return drainTo(c, Integer.MAX_VALUE); |
723 |
} |
724 |
|
725 |
/** |
726 |
* @throws UnsupportedOperationException {@inheritDoc} |
727 |
* @throws ClassCastException {@inheritDoc} |
728 |
* @throws NullPointerException {@inheritDoc} |
729 |
* @throws IllegalArgumentException {@inheritDoc} |
730 |
*/ |
731 |
public int drainTo(Collection<? super E> c, int maxElements) { |
732 |
if (c == null) |
733 |
throw new NullPointerException(); |
734 |
if (c == this) |
735 |
throw new IllegalArgumentException(); |
736 |
if (maxElements <= 0) |
737 |
return 0; |
738 |
final ReentrantLock lock = this.lock; |
739 |
lock.lock(); |
740 |
try { |
741 |
int n = Math.min(maxElements, count); |
742 |
for (int i = 0; i < n; i++) { |
743 |
c.add(first.item); // In this order, in case add() throws. |
744 |
unlinkFirst(); |
745 |
} |
746 |
return n; |
747 |
} finally { |
748 |
// checkInvariants(); |
749 |
lock.unlock(); |
750 |
} |
751 |
} |
752 |
|
753 |
// Stack methods |
754 |
|
755 |
/** |
756 |
* @throws IllegalStateException if this deque is full |
757 |
* @throws NullPointerException {@inheritDoc} |
758 |
*/ |
759 |
public void push(E e) { |
760 |
addFirst(e); |
761 |
} |
762 |
|
763 |
/** |
764 |
* @throws NoSuchElementException {@inheritDoc} |
765 |
*/ |
766 |
public E pop() { |
767 |
return removeFirst(); |
768 |
} |
769 |
|
770 |
// Collection methods |
771 |
|
772 |
/** |
773 |
* Removes the first occurrence of the specified element from this deque. |
774 |
* If the deque does not contain the element, it is unchanged. |
775 |
* More formally, removes the first element {@code e} such that |
776 |
* {@code o.equals(e)} (if such an element exists). |
777 |
* Returns {@code true} if this deque contained the specified element |
778 |
* (or equivalently, if this deque changed as a result of the call). |
779 |
* |
780 |
* <p>This method is equivalent to |
781 |
* {@link #removeFirstOccurrence(Object) removeFirstOccurrence}. |
782 |
* |
783 |
* @param o element to be removed from this deque, if present |
784 |
* @return {@code true} if this deque changed as a result of the call |
785 |
*/ |
786 |
public boolean remove(Object o) { |
787 |
return removeFirstOccurrence(o); |
788 |
} |
789 |
|
790 |
/** |
791 |
* Returns the number of elements in this deque. |
792 |
* |
793 |
* @return the number of elements in this deque |
794 |
*/ |
795 |
public int size() { |
796 |
final ReentrantLock lock = this.lock; |
797 |
lock.lock(); |
798 |
try { |
799 |
return count; |
800 |
} finally { |
801 |
// checkInvariants(); |
802 |
lock.unlock(); |
803 |
} |
804 |
} |
805 |
|
806 |
/** |
807 |
* Returns {@code true} if this deque contains the specified element. |
808 |
* More formally, returns {@code true} if and only if this deque contains |
809 |
* at least one element {@code e} such that {@code o.equals(e)}. |
810 |
* |
811 |
* @param o object to be checked for containment in this deque |
812 |
* @return {@code true} if this deque contains the specified element |
813 |
*/ |
814 |
public boolean contains(Object o) { |
815 |
if (o == null) return false; |
816 |
final ReentrantLock lock = this.lock; |
817 |
lock.lock(); |
818 |
try { |
819 |
for (Node<E> p = first; p != null; p = p.next) |
820 |
if (o.equals(p.item)) |
821 |
return true; |
822 |
return false; |
823 |
} finally { |
824 |
// checkInvariants(); |
825 |
lock.unlock(); |
826 |
} |
827 |
} |
828 |
|
829 |
/* |
830 |
* TODO: Add support for more efficient bulk operations. |
831 |
* |
832 |
* We don't want to acquire the lock for every iteration, but we |
833 |
* also want other threads a chance to interact with the |
834 |
* collection, especially when count is close to capacity. |
835 |
*/ |
836 |
|
837 |
// /** |
838 |
// * Adds all of the elements in the specified collection to this |
839 |
// * queue. Attempts to addAll of a queue to itself result in |
840 |
// * {@code IllegalArgumentException}. Further, the behavior of |
841 |
// * this operation is undefined if the specified collection is |
842 |
// * modified while the operation is in progress. |
843 |
// * |
844 |
// * @param c collection containing elements to be added to this queue |
845 |
// * @return {@code true} if this queue changed as a result of the call |
846 |
// * @throws ClassCastException {@inheritDoc} |
847 |
// * @throws NullPointerException {@inheritDoc} |
848 |
// * @throws IllegalArgumentException {@inheritDoc} |
849 |
// * @throws IllegalStateException if this deque is full |
850 |
// * @see #add(Object) |
851 |
// */ |
852 |
// public boolean addAll(Collection<? extends E> c) { |
853 |
// if (c == null) |
854 |
// throw new NullPointerException(); |
855 |
// if (c == this) |
856 |
// throw new IllegalArgumentException(); |
857 |
// final ReentrantLock lock = this.lock; |
858 |
// lock.lock(); |
859 |
// try { |
860 |
// boolean modified = false; |
861 |
// for (E e : c) |
862 |
// if (linkLast(e)) |
863 |
// modified = true; |
864 |
// return modified; |
865 |
// } finally { |
866 |
// lock.unlock(); |
867 |
// } |
868 |
// } |
869 |
|
870 |
/** |
871 |
* Returns an array containing all of the elements in this deque, in |
872 |
* proper sequence (from first to last element). |
873 |
* |
874 |
* <p>The returned array will be "safe" in that no references to it are |
875 |
* maintained by this deque. (In other words, this method must allocate |
876 |
* a new array). The caller is thus free to modify the returned array. |
877 |
* |
878 |
* <p>This method acts as bridge between array-based and collection-based |
879 |
* APIs. |
880 |
* |
881 |
* @return an array containing all of the elements in this deque |
882 |
*/ |
883 |
@SuppressWarnings("unchecked") |
884 |
public Object[] toArray() { |
885 |
final ReentrantLock lock = this.lock; |
886 |
lock.lock(); |
887 |
try { |
888 |
Object[] a = new Object[count]; |
889 |
int k = 0; |
890 |
for (Node<E> p = first; p != null; p = p.next) |
891 |
a[k++] = p.item; |
892 |
return a; |
893 |
} finally { |
894 |
// checkInvariants(); |
895 |
lock.unlock(); |
896 |
} |
897 |
} |
898 |
|
899 |
/** |
900 |
* Returns an array containing all of the elements in this deque, in |
901 |
* proper sequence; the runtime type of the returned array is that of |
902 |
* the specified array. If the deque fits in the specified array, it |
903 |
* is returned therein. Otherwise, a new array is allocated with the |
904 |
* runtime type of the specified array and the size of this deque. |
905 |
* |
906 |
* <p>If this deque fits in the specified array with room to spare |
907 |
* (i.e., the array has more elements than this deque), the element in |
908 |
* the array immediately following the end of the deque is set to |
909 |
* {@code null}. |
910 |
* |
911 |
* <p>Like the {@link #toArray()} method, this method acts as bridge between |
912 |
* array-based and collection-based APIs. Further, this method allows |
913 |
* precise control over the runtime type of the output array, and may, |
914 |
* under certain circumstances, be used to save allocation costs. |
915 |
* |
916 |
* <p>Suppose {@code x} is a deque known to contain only strings. |
917 |
* The following code can be used to dump the deque into a newly |
918 |
* allocated array of {@code String}: |
919 |
* |
920 |
* <pre> {@code String[] y = x.toArray(new String[0]);}</pre> |
921 |
* |
922 |
* Note that {@code toArray(new Object[0])} is identical in function to |
923 |
* {@code toArray()}. |
924 |
* |
925 |
* @param a the array into which the elements of the deque are to |
926 |
* be stored, if it is big enough; otherwise, a new array of the |
927 |
* same runtime type is allocated for this purpose |
928 |
* @return an array containing all of the elements in this deque |
929 |
* @throws ArrayStoreException if the runtime type of the specified array |
930 |
* is not a supertype of the runtime type of every element in |
931 |
* this deque |
932 |
* @throws NullPointerException if the specified array is null |
933 |
*/ |
934 |
@SuppressWarnings("unchecked") |
935 |
public <T> T[] toArray(T[] a) { |
936 |
final ReentrantLock lock = this.lock; |
937 |
lock.lock(); |
938 |
try { |
939 |
if (a.length < count) |
940 |
a = (T[])java.lang.reflect.Array.newInstance |
941 |
(a.getClass().getComponentType(), count); |
942 |
|
943 |
int k = 0; |
944 |
for (Node<E> p = first; p != null; p = p.next) |
945 |
a[k++] = (T)p.item; |
946 |
if (a.length > k) |
947 |
a[k] = null; |
948 |
return a; |
949 |
} finally { |
950 |
// checkInvariants(); |
951 |
lock.unlock(); |
952 |
} |
953 |
} |
954 |
|
955 |
public String toString() { |
956 |
return Helpers.collectionToString(this); |
957 |
} |
958 |
|
959 |
/** |
960 |
* Atomically removes all of the elements from this deque. |
961 |
* The deque will be empty after this call returns. |
962 |
*/ |
963 |
public void clear() { |
964 |
final ReentrantLock lock = this.lock; |
965 |
lock.lock(); |
966 |
try { |
967 |
for (Node<E> f = first; f != null; ) { |
968 |
f.item = null; |
969 |
Node<E> n = f.next; |
970 |
f.prev = null; |
971 |
f.next = null; |
972 |
f = n; |
973 |
} |
974 |
first = last = null; |
975 |
count = 0; |
976 |
notFull.signalAll(); |
977 |
} finally { |
978 |
// checkInvariants(); |
979 |
lock.unlock(); |
980 |
} |
981 |
} |
982 |
|
983 |
/** |
984 |
* Returns an iterator over the elements in this deque in proper sequence. |
985 |
* The elements will be returned in order from first (head) to last (tail). |
986 |
* |
987 |
* <p>The returned iterator is |
988 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
989 |
* |
990 |
* @return an iterator over the elements in this deque in proper sequence |
991 |
*/ |
992 |
public Iterator<E> iterator() { |
993 |
return new Itr(); |
994 |
} |
995 |
|
996 |
/** |
997 |
* Returns an iterator over the elements in this deque in reverse |
998 |
* sequential order. The elements will be returned in order from |
999 |
* last (tail) to first (head). |
1000 |
* |
1001 |
* <p>The returned iterator is |
1002 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
1003 |
* |
1004 |
* @return an iterator over the elements in this deque in reverse order |
1005 |
*/ |
1006 |
public Iterator<E> descendingIterator() { |
1007 |
return new DescendingItr(); |
1008 |
} |
1009 |
|
1010 |
/** |
1011 |
* Base class for LinkedBlockingDeque iterators. |
1012 |
*/ |
1013 |
private abstract class AbstractItr implements Iterator<E> { |
1014 |
/** |
1015 |
* The next node to return in next(). |
1016 |
*/ |
1017 |
Node<E> next; |
1018 |
|
1019 |
/** |
1020 |
* nextItem holds on to item fields because once we claim that |
1021 |
* an element exists in hasNext(), we must return item read |
1022 |
* under lock (in advance()) even if it was in the process of |
1023 |
* being removed when hasNext() was called. |
1024 |
*/ |
1025 |
E nextItem; |
1026 |
|
1027 |
/** |
1028 |
* Node returned by most recent call to next. Needed by remove. |
1029 |
* Reset to null if this element is deleted by a call to remove. |
1030 |
*/ |
1031 |
private Node<E> lastRet; |
1032 |
|
1033 |
abstract Node<E> firstNode(); |
1034 |
abstract Node<E> nextNode(Node<E> n); |
1035 |
|
1036 |
private Node<E> succ(Node<E> p) { |
1037 |
return (p == (p = nextNode(p))) ? firstNode() : p; |
1038 |
} |
1039 |
|
1040 |
AbstractItr() { |
1041 |
// set to initial position |
1042 |
final ReentrantLock lock = LinkedBlockingDeque.this.lock; |
1043 |
lock.lock(); |
1044 |
try { |
1045 |
if ((next = firstNode()) != null) |
1046 |
nextItem = next.item; |
1047 |
} finally { |
1048 |
// checkInvariants(); |
1049 |
lock.unlock(); |
1050 |
} |
1051 |
} |
1052 |
|
1053 |
/** |
1054 |
* Advances next. |
1055 |
*/ |
1056 |
void advance() { |
1057 |
// assert next != null; |
1058 |
final ReentrantLock lock = LinkedBlockingDeque.this.lock; |
1059 |
lock.lock(); |
1060 |
try { |
1061 |
// Chains of deleted nodes ending in null or self-links |
1062 |
// are possible if multiple interior nodes are removed. |
1063 |
for (next = nextNode(next);; next = succ(next)) { |
1064 |
if (next == null) { |
1065 |
nextItem = null; |
1066 |
break; |
1067 |
} else if ((nextItem = next.item) != null) |
1068 |
break; |
1069 |
} |
1070 |
} finally { |
1071 |
// checkInvariants(); |
1072 |
lock.unlock(); |
1073 |
} |
1074 |
} |
1075 |
|
1076 |
public boolean hasNext() { |
1077 |
return next != null; |
1078 |
} |
1079 |
|
1080 |
public E next() { |
1081 |
if (next == null) |
1082 |
throw new NoSuchElementException(); |
1083 |
lastRet = next; |
1084 |
E x = nextItem; |
1085 |
advance(); |
1086 |
return x; |
1087 |
} |
1088 |
|
1089 |
public void remove() { |
1090 |
Node<E> n = lastRet; |
1091 |
if (n == null) |
1092 |
throw new IllegalStateException(); |
1093 |
lastRet = null; |
1094 |
final ReentrantLock lock = LinkedBlockingDeque.this.lock; |
1095 |
lock.lock(); |
1096 |
try { |
1097 |
if (n.item != null) |
1098 |
unlink(n); |
1099 |
} finally { |
1100 |
// checkInvariants(); |
1101 |
lock.unlock(); |
1102 |
} |
1103 |
} |
1104 |
} |
1105 |
|
1106 |
/** Forward iterator */ |
1107 |
private class Itr extends AbstractItr { |
1108 |
Node<E> firstNode() { return first; } |
1109 |
Node<E> nextNode(Node<E> n) { return n.next; } |
1110 |
} |
1111 |
|
1112 |
/** Descending iterator */ |
1113 |
private class DescendingItr extends AbstractItr { |
1114 |
Node<E> firstNode() { return last; } |
1115 |
Node<E> nextNode(Node<E> n) { return n.prev; } |
1116 |
} |
1117 |
|
1118 |
/** |
1119 |
* A customized variant of Spliterators.IteratorSpliterator. |
1120 |
* Keep this class in sync with (very similar) LBQSpliterator. |
1121 |
*/ |
1122 |
private final class LBDSpliterator implements Spliterator<E> { |
1123 |
static final int MAX_BATCH = 1 << 25; // max batch array size; |
1124 |
Node<E> current; // current node; null until initialized |
1125 |
int batch; // batch size for splits |
1126 |
boolean exhausted; // true when no more nodes |
1127 |
long est = size(); // size estimate |
1128 |
|
1129 |
LBDSpliterator() {} |
1130 |
|
1131 |
private Node<E> succ(Node<E> p) { |
1132 |
return (p == (p = p.next)) ? first : p; |
1133 |
} |
1134 |
|
1135 |
public long estimateSize() { return est; } |
1136 |
|
1137 |
public Spliterator<E> trySplit() { |
1138 |
Node<E> h; |
1139 |
int b = batch; |
1140 |
int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1; |
1141 |
if (!exhausted && |
1142 |
((h = current) != null || (h = first) != null) |
1143 |
&& h.next != null) { |
1144 |
Object[] a = new Object[n]; |
1145 |
final ReentrantLock lock = LinkedBlockingDeque.this.lock; |
1146 |
int i = 0; |
1147 |
Node<E> p = current; |
1148 |
lock.lock(); |
1149 |
try { |
1150 |
if (p != null || (p = first) != null) |
1151 |
for (; p != null && i < n; p = succ(p)) |
1152 |
if ((a[i] = p.item) != null) |
1153 |
i++; |
1154 |
} finally { |
1155 |
// checkInvariants(); |
1156 |
lock.unlock(); |
1157 |
} |
1158 |
if ((current = p) == null) { |
1159 |
est = 0L; |
1160 |
exhausted = true; |
1161 |
} |
1162 |
else if ((est -= i) < 0L) |
1163 |
est = 0L; |
1164 |
if (i > 0) { |
1165 |
batch = i; |
1166 |
return Spliterators.spliterator |
1167 |
(a, 0, i, (Spliterator.ORDERED | |
1168 |
Spliterator.NONNULL | |
1169 |
Spliterator.CONCURRENT)); |
1170 |
} |
1171 |
} |
1172 |
return null; |
1173 |
} |
1174 |
|
1175 |
public void forEachRemaining(Consumer<? super E> action) { |
1176 |
if (action == null) throw new NullPointerException(); |
1177 |
if (!exhausted) { |
1178 |
exhausted = true; |
1179 |
final ReentrantLock lock = LinkedBlockingDeque.this.lock; |
1180 |
Node<E> p = current; |
1181 |
current = null; |
1182 |
do { |
1183 |
E e = null; |
1184 |
lock.lock(); |
1185 |
try { |
1186 |
if (p != null || (p = first) != null) |
1187 |
do { |
1188 |
e = p.item; |
1189 |
p = succ(p); |
1190 |
} while (e == null && p != null); |
1191 |
} finally { |
1192 |
// checkInvariants(); |
1193 |
lock.unlock(); |
1194 |
} |
1195 |
if (e != null) |
1196 |
action.accept(e); |
1197 |
} while (p != null); |
1198 |
} |
1199 |
} |
1200 |
|
1201 |
public boolean tryAdvance(Consumer<? super E> action) { |
1202 |
if (action == null) throw new NullPointerException(); |
1203 |
if (!exhausted) { |
1204 |
final ReentrantLock lock = LinkedBlockingDeque.this.lock; |
1205 |
Node<E> p = current; |
1206 |
E e = null; |
1207 |
lock.lock(); |
1208 |
try { |
1209 |
if (p != null || (p = first) != null) |
1210 |
do { |
1211 |
e = p.item; |
1212 |
p = succ(p); |
1213 |
} while (e == null && p != null); |
1214 |
} finally { |
1215 |
// checkInvariants(); |
1216 |
lock.unlock(); |
1217 |
} |
1218 |
exhausted = ((current = p) == null); |
1219 |
if (e != null) { |
1220 |
action.accept(e); |
1221 |
return true; |
1222 |
} |
1223 |
} |
1224 |
return false; |
1225 |
} |
1226 |
|
1227 |
public int characteristics() { |
1228 |
return (Spliterator.ORDERED | |
1229 |
Spliterator.NONNULL | |
1230 |
Spliterator.CONCURRENT); |
1231 |
} |
1232 |
} |
1233 |
|
1234 |
/** |
1235 |
* Returns a {@link Spliterator} over the elements in this deque. |
1236 |
* |
1237 |
* <p>The returned spliterator is |
1238 |
* <a href="package-summary.html#Weakly"><i>weakly consistent</i></a>. |
1239 |
* |
1240 |
* <p>The {@code Spliterator} reports {@link Spliterator#CONCURRENT}, |
1241 |
* {@link Spliterator#ORDERED}, and {@link Spliterator#NONNULL}. |
1242 |
* |
1243 |
* @implNote |
1244 |
* The {@code Spliterator} implements {@code trySplit} to permit limited |
1245 |
* parallelism. |
1246 |
* |
1247 |
* @return a {@code Spliterator} over the elements in this deque |
1248 |
* @since 1.8 |
1249 |
*/ |
1250 |
public Spliterator<E> spliterator() { |
1251 |
return new LBDSpliterator(); |
1252 |
} |
1253 |
|
1254 |
/** |
1255 |
* Saves this deque to a stream (that is, serializes it). |
1256 |
* |
1257 |
* @param s the stream |
1258 |
* @throws java.io.IOException if an I/O error occurs |
1259 |
* @serialData The capacity (int), followed by elements (each an |
1260 |
* {@code Object}) in the proper order, followed by a null |
1261 |
*/ |
1262 |
private void writeObject(java.io.ObjectOutputStream s) |
1263 |
throws java.io.IOException { |
1264 |
final ReentrantLock lock = this.lock; |
1265 |
lock.lock(); |
1266 |
try { |
1267 |
// Write out capacity and any hidden stuff |
1268 |
s.defaultWriteObject(); |
1269 |
// Write out all elements in the proper order. |
1270 |
for (Node<E> p = first; p != null; p = p.next) |
1271 |
s.writeObject(p.item); |
1272 |
// Use trailing null as sentinel |
1273 |
s.writeObject(null); |
1274 |
} finally { |
1275 |
// checkInvariants(); |
1276 |
lock.unlock(); |
1277 |
} |
1278 |
} |
1279 |
|
1280 |
/** |
1281 |
* Reconstitutes this deque from a stream (that is, deserializes it). |
1282 |
* @param s the stream |
1283 |
* @throws ClassNotFoundException if the class of a serialized object |
1284 |
* could not be found |
1285 |
* @throws java.io.IOException if an I/O error occurs |
1286 |
*/ |
1287 |
private void readObject(java.io.ObjectInputStream s) |
1288 |
throws java.io.IOException, ClassNotFoundException { |
1289 |
s.defaultReadObject(); |
1290 |
count = 0; |
1291 |
first = null; |
1292 |
last = null; |
1293 |
// Read in all elements and place in queue |
1294 |
for (;;) { |
1295 |
@SuppressWarnings("unchecked") |
1296 |
E item = (E)s.readObject(); |
1297 |
if (item == null) |
1298 |
break; |
1299 |
add(item); |
1300 |
} |
1301 |
} |
1302 |
|
1303 |
void checkInvariants() { |
1304 |
// assert lock.isHeldByCurrentThread(); |
1305 |
// Nodes may get self-linked or lose their item, but only |
1306 |
// after being unlinked and becoming unreachable from first. |
1307 |
for (Node<E> p = first; p != null; p = p.next) { |
1308 |
// assert p.next != p; |
1309 |
// assert p.item != null; |
1310 |
} |
1311 |
} |
1312 |
|
1313 |
} |