ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/LinkedBlockingDeque.java
Revision: 1.41
Committed: Sun Mar 17 15:34:21 2013 UTC (11 years, 2 months ago) by jsr166
Branch: MAIN
Changes since 1.40: +3 -3 lines
Log Message:
whitespace

File Contents

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