2 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 * This code is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License version 2 only, as
6 * published by the Free Software Foundation. Oracle designates this
7 * particular file as subject to the "Classpath" exception as provided
8 * by Oracle in the LICENSE file that accompanied this code.
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
26 * This file is available under and governed by the GNU General Public
27 * License version 2 only, as published by the Free Software Foundation.
28 * However, the following notice accompanied the original version of this
31 * Written by Doug Lea with assistance from members of JCP JSR-166
32 * Expert Group and released to the public domain, as explained at
33 * http://creativecommons.org/publicdomain/zero/1.0/
36 package java.util.concurrent;
38 import java.util.AbstractQueue;
39 import java.util.Collection;
40 import java.util.Iterator;
41 import java.util.NoSuchElementException;
42 import java.util.concurrent.locks.Condition;
43 import java.util.concurrent.locks.ReentrantLock;
46 * An optionally-bounded {@linkplain BlockingDeque blocking deque} based on
49 * <p> The optional capacity bound constructor argument serves as a
50 * way to prevent excessive expansion. The capacity, if unspecified,
51 * is equal to {@link Integer#MAX_VALUE}. Linked nodes are
52 * dynamically created upon each insertion unless this would bring the
53 * deque above capacity.
55 * <p>Most operations run in constant time (ignoring time spent
56 * blocking). Exceptions include {@link #remove(Object) remove},
57 * {@link #removeFirstOccurrence removeFirstOccurrence}, {@link
58 * #removeLastOccurrence removeLastOccurrence}, {@link #contains
59 * contains}, {@link #iterator iterator.remove()}, and the bulk
60 * operations, all of which run in linear time.
62 * <p>This class and its iterator implement all of the
63 * <em>optional</em> methods of the {@link Collection} and {@link
64 * Iterator} interfaces.
66 * <p>This class is a member of the
67 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
68 * Java Collections Framework</a>.
72 * @param <E> the type of elements held in this collection
74 public class LinkedBlockingDeque<E>
75 extends AbstractQueue<E>
76 implements BlockingDeque<E>, java.io.Serializable {
79 * Implemented as a simple doubly-linked list protected by a
80 * single lock and using conditions to manage blocking.
82 * To implement weakly consistent iterators, it appears we need to
83 * keep all Nodes GC-reachable from a predecessor dequeued Node.
84 * That would cause two problems:
85 * - allow a rogue Iterator to cause unbounded memory retention
86 * - cause cross-generational linking of old Nodes to new Nodes if
87 * a Node was tenured while live, which generational GCs have a
88 * hard time dealing with, causing repeated major collections.
89 * However, only non-deleted Nodes need to be reachable from
90 * dequeued Nodes, and reachability does not necessarily have to
91 * be of the kind understood by the GC. We use the trick of
92 * linking a Node that has just been dequeued to itself. Such a
93 * self-link implicitly means to jump to "first" (for next links)
94 * or "last" (for prev links).
98 * We have "diamond" multiple interface/abstract class inheritance
99 * here, and that introduces ambiguities. Often we want the
100 * BlockingDeque javadoc combined with the AbstractQueue
101 * implementation, so a lot of method specs are duplicated here.
104 private static final long serialVersionUID = -387911632671998426L;
106 /** Doubly-linked list node class */
107 static final class Node<E> {
109 * The item, or null if this node has been removed.
115 * - the real predecessor Node
116 * - this Node, meaning the predecessor is tail
117 * - null, meaning there is no predecessor
123 * - the real successor Node
124 * - this Node, meaning the successor is head
125 * - null, meaning there is no successor
135 * Pointer to first node.
136 * Invariant: (first == null && last == null) ||
137 * (first.prev == null && first.item != null)
139 transient Node<E> first;
142 * Pointer to last node.
143 * Invariant: (first == null && last == null) ||
144 * (last.next == null && last.item != null)
146 transient Node<E> last;
148 /** Number of items in the deque */
149 private transient int count;
151 /** Maximum number of items in the deque */
152 private final int capacity;
154 /** Main lock guarding all access */
155 final ReentrantLock lock = new ReentrantLock();
157 /** Condition for waiting takes */
158 private final Condition notEmpty = lock.newCondition();
160 /** Condition for waiting puts */
161 private final Condition notFull = lock.newCondition();
164 * Creates a {@code LinkedBlockingDeque} with a capacity of
165 * {@link Integer#MAX_VALUE}.
167 public LinkedBlockingDeque() {
168 this(Integer.MAX_VALUE);
172 * Creates a {@code LinkedBlockingDeque} with the given (fixed) capacity.
174 * @param capacity the capacity of this deque
175 * @throws IllegalArgumentException if {@code capacity} is less than 1
177 public LinkedBlockingDeque(int capacity) {
178 if (capacity <= 0) throw new IllegalArgumentException();
179 this.capacity = capacity;
183 * Creates a {@code LinkedBlockingDeque} with a capacity of
184 * {@link Integer#MAX_VALUE}, initially containing the elements of
185 * the given collection, added in traversal order of the
186 * collection's iterator.
188 * @param c the collection of elements to initially contain
189 * @throws NullPointerException if the specified collection or any
190 * of its elements are null
192 public LinkedBlockingDeque(Collection<? extends E> c) {
193 this(Integer.MAX_VALUE);
194 final ReentrantLock lock = this.lock;
195 lock.lock(); // Never contended, but necessary for visibility
199 throw new NullPointerException();
200 if (!linkLast(new Node<E>(e)))
201 throw new IllegalStateException("Deque full");
209 // Basic linking and unlinking operations, called only while holding lock
212 * Links node as first element, or returns false if full.
214 private boolean linkFirst(Node<E> node) {
215 // assert lock.isHeldByCurrentThread();
216 if (count >= capacity)
231 * Links node as last element, or returns false if full.
233 private boolean linkLast(Node<E> node) {
234 // assert lock.isHeldByCurrentThread();
235 if (count >= capacity)
250 * Removes and returns first element, or null if empty.
252 private E unlinkFirst() {
253 // assert lock.isHeldByCurrentThread();
260 f.next = f; // help GC
272 * Removes and returns last element, or null if empty.
274 private E unlinkLast() {
275 // assert lock.isHeldByCurrentThread();
282 l.prev = l; // help GC
296 void unlink(Node<E> x) {
297 // assert lock.isHeldByCurrentThread();
302 } else if (n == null) {
308 // Don't mess with x's links. They may still be in use by
315 // BlockingDeque methods
318 * @throws IllegalStateException {@inheritDoc}
319 * @throws NullPointerException {@inheritDoc}
321 public void addFirst(E e) {
323 throw new IllegalStateException("Deque full");
327 * @throws IllegalStateException {@inheritDoc}
328 * @throws NullPointerException {@inheritDoc}
330 public void addLast(E e) {
332 throw new IllegalStateException("Deque full");
336 * @throws NullPointerException {@inheritDoc}
338 public boolean offerFirst(E e) {
339 if (e == null) throw new NullPointerException();
340 Node<E> node = new Node<E>(e);
341 final ReentrantLock lock = this.lock;
344 return linkFirst(node);
351 * @throws NullPointerException {@inheritDoc}
353 public boolean offerLast(E e) {
354 if (e == null) throw new NullPointerException();
355 Node<E> node = new Node<E>(e);
356 final ReentrantLock lock = this.lock;
359 return linkLast(node);
366 * @throws NullPointerException {@inheritDoc}
367 * @throws InterruptedException {@inheritDoc}
369 public void putFirst(E e) throws InterruptedException {
370 if (e == null) throw new NullPointerException();
371 Node<E> node = new Node<E>(e);
372 final ReentrantLock lock = this.lock;
375 while (!linkFirst(node))
383 * @throws NullPointerException {@inheritDoc}
384 * @throws InterruptedException {@inheritDoc}
386 public void putLast(E e) throws InterruptedException {
387 if (e == null) throw new NullPointerException();
388 Node<E> node = new Node<E>(e);
389 final ReentrantLock lock = this.lock;
392 while (!linkLast(node))
400 * @throws NullPointerException {@inheritDoc}
401 * @throws InterruptedException {@inheritDoc}
403 public boolean offerFirst(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();
411 while (!linkFirst(node)) {
414 nanos = notFull.awaitNanos(nanos);
423 * @throws NullPointerException {@inheritDoc}
424 * @throws InterruptedException {@inheritDoc}
426 public boolean offerLast(E e, long timeout, TimeUnit unit)
427 throws InterruptedException {
428 if (e == null) throw new NullPointerException();
429 Node<E> node = new Node<E>(e);
430 long nanos = unit.toNanos(timeout);
431 final ReentrantLock lock = this.lock;
432 lock.lockInterruptibly();
434 while (!linkLast(node)) {
437 nanos = notFull.awaitNanos(nanos);
446 * @throws NoSuchElementException {@inheritDoc}
448 public E removeFirst() {
450 if (x == null) throw new NoSuchElementException();
455 * @throws NoSuchElementException {@inheritDoc}
457 public E removeLast() {
459 if (x == null) throw new NoSuchElementException();
463 public E pollFirst() {
464 final ReentrantLock lock = this.lock;
467 return unlinkFirst();
473 public E pollLast() {
474 final ReentrantLock lock = this.lock;
483 public E takeFirst() throws InterruptedException {
484 final ReentrantLock lock = this.lock;
488 while ( (x = unlinkFirst()) == null)
496 public E takeLast() throws InterruptedException {
497 final ReentrantLock lock = this.lock;
501 while ( (x = unlinkLast()) == null)
509 public E pollFirst(long timeout, TimeUnit unit)
510 throws InterruptedException {
511 long nanos = unit.toNanos(timeout);
512 final ReentrantLock lock = this.lock;
513 lock.lockInterruptibly();
516 while ( (x = unlinkFirst()) == null) {
519 nanos = notEmpty.awaitNanos(nanos);
527 public E pollLast(long timeout, TimeUnit unit)
528 throws InterruptedException {
529 long nanos = unit.toNanos(timeout);
530 final ReentrantLock lock = this.lock;
531 lock.lockInterruptibly();
534 while ( (x = unlinkLast()) == null) {
537 nanos = notEmpty.awaitNanos(nanos);
546 * @throws NoSuchElementException {@inheritDoc}
548 public E getFirst() {
550 if (x == null) throw new NoSuchElementException();
555 * @throws NoSuchElementException {@inheritDoc}
559 if (x == null) throw new NoSuchElementException();
563 public E peekFirst() {
564 final ReentrantLock lock = this.lock;
567 return (first == null) ? null : first.item;
573 public E peekLast() {
574 final ReentrantLock lock = this.lock;
577 return (last == null) ? null : last.item;
583 public boolean removeFirstOccurrence(Object o) {
584 if (o == null) return false;
585 final ReentrantLock lock = this.lock;
588 for (Node<E> p = first; p != null; p = p.next) {
589 if (o.equals(p.item)) {
600 public boolean removeLastOccurrence(Object o) {
601 if (o == null) return false;
602 final ReentrantLock lock = this.lock;
605 for (Node<E> p = last; p != null; p = p.prev) {
606 if (o.equals(p.item)) {
617 // BlockingQueue methods
620 * Inserts the specified element at the end of this deque unless it would
621 * violate capacity restrictions. When using a capacity-restricted deque,
622 * it is generally preferable to use method {@link #offer(Object) offer}.
624 * <p>This method is equivalent to {@link #addLast}.
626 * @throws IllegalStateException if the element cannot be added at this
627 * time due to capacity restrictions
628 * @throws NullPointerException if the specified element is null
630 public boolean add(E e) {
636 * @throws NullPointerException if the specified element is null
638 public boolean offer(E e) {
643 * @throws NullPointerException {@inheritDoc}
644 * @throws InterruptedException {@inheritDoc}
646 public void put(E e) throws InterruptedException {
651 * @throws NullPointerException {@inheritDoc}
652 * @throws InterruptedException {@inheritDoc}
654 public boolean offer(E e, long timeout, TimeUnit unit)
655 throws InterruptedException {
656 return offerLast(e, timeout, unit);
660 * Retrieves and removes the head of the queue represented by this deque.
661 * This method differs from {@link #poll poll} only in that it throws an
662 * exception if this deque is empty.
664 * <p>This method is equivalent to {@link #removeFirst() removeFirst}.
666 * @return the head of the queue represented by this deque
667 * @throws NoSuchElementException if this deque is empty
670 return removeFirst();
677 public E take() throws InterruptedException {
681 public E poll(long timeout, TimeUnit unit) throws InterruptedException {
682 return pollFirst(timeout, unit);
686 * Retrieves, but does not remove, the head of the queue represented by
687 * this deque. This method differs from {@link #peek peek} only in that
688 * it throws an exception if this deque is empty.
690 * <p>This method is equivalent to {@link #getFirst() getFirst}.
692 * @return the head of the queue represented by this deque
693 * @throws NoSuchElementException if this deque is empty
704 * Returns the number of additional elements that this deque can ideally
705 * (in the absence of memory or resource constraints) accept without
706 * blocking. This is always equal to the initial capacity of this deque
707 * less the current {@code size} of this deque.
709 * <p>Note that you <em>cannot</em> always tell if an attempt to insert
710 * an element will succeed by inspecting {@code remainingCapacity}
711 * because it may be the case that another thread is about to
712 * insert or remove an element.
714 public int remainingCapacity() {
715 final ReentrantLock lock = this.lock;
718 return capacity - count;
725 * @throws UnsupportedOperationException {@inheritDoc}
726 * @throws ClassCastException {@inheritDoc}
727 * @throws NullPointerException {@inheritDoc}
728 * @throws IllegalArgumentException {@inheritDoc}
730 public int drainTo(Collection<? super E> c) {
731 return drainTo(c, Integer.MAX_VALUE);
735 * @throws UnsupportedOperationException {@inheritDoc}
736 * @throws ClassCastException {@inheritDoc}
737 * @throws NullPointerException {@inheritDoc}
738 * @throws IllegalArgumentException {@inheritDoc}
740 public int drainTo(Collection<? super E> c, int maxElements) {
742 throw new NullPointerException();
744 throw new IllegalArgumentException();
745 final ReentrantLock lock = this.lock;
748 int n = Math.min(maxElements, count);
749 for (int i = 0; i < n; i++) {
750 c.add(first.item); // In this order, in case add() throws.
762 * @throws IllegalStateException {@inheritDoc}
763 * @throws NullPointerException {@inheritDoc}
765 public void push(E e) {
770 * @throws NoSuchElementException {@inheritDoc}
773 return removeFirst();
776 // Collection methods
779 * Removes the first occurrence of the specified element from this deque.
780 * If the deque does not contain the element, it is unchanged.
781 * More formally, removes the first element {@code e} such that
782 * {@code o.equals(e)} (if such an element exists).
783 * Returns {@code true} if this deque contained the specified element
784 * (or equivalently, if this deque changed as a result of the call).
786 * <p>This method is equivalent to
787 * {@link #removeFirstOccurrence(Object) removeFirstOccurrence}.
789 * @param o element to be removed from this deque, if present
790 * @return {@code true} if this deque changed as a result of the call
792 public boolean remove(Object o) {
793 return removeFirstOccurrence(o);
797 * Returns the number of elements in this deque.
799 * @return the number of elements in this deque
802 final ReentrantLock lock = this.lock;
812 * Returns {@code true} if this deque contains the specified element.
813 * More formally, returns {@code true} if and only if this deque contains
814 * at least one element {@code e} such that {@code o.equals(e)}.
816 * @param o object to be checked for containment in this deque
817 * @return {@code true} if this deque contains the specified element
819 public boolean contains(Object o) {
820 if (o == null) return false;
821 final ReentrantLock lock = this.lock;
824 for (Node<E> p = first; p != null; p = p.next)
825 if (o.equals(p.item))
834 * TODO: Add support for more efficient bulk operations.
836 * We don't want to acquire the lock for every iteration, but we
837 * also want other threads a chance to interact with the
838 * collection, especially when count is close to capacity.
842 // * Adds all of the elements in the specified collection to this
843 // * queue. Attempts to addAll of a queue to itself result in
844 // * {@code IllegalArgumentException}. Further, the behavior of
845 // * this operation is undefined if the specified collection is
846 // * modified while the operation is in progress.
848 // * @param c collection containing elements to be added to this queue
849 // * @return {@code true} if this queue changed as a result of the call
850 // * @throws ClassCastException {@inheritDoc}
851 // * @throws NullPointerException {@inheritDoc}
852 // * @throws IllegalArgumentException {@inheritDoc}
853 // * @throws IllegalStateException {@inheritDoc}
854 // * @see #add(Object)
856 // public boolean addAll(Collection<? extends E> c) {
858 // throw new NullPointerException();
860 // throw new IllegalArgumentException();
861 // final ReentrantLock lock = this.lock;
864 // boolean modified = false;
875 * Returns an array containing all of the elements in this deque, in
876 * proper sequence (from first to last element).
878 * <p>The returned array will be "safe" in that no references to it are
879 * maintained by this deque. (In other words, this method must allocate
880 * a new array). The caller is thus free to modify the returned array.
882 * <p>This method acts as bridge between array-based and collection-based
885 * @return an array containing all of the elements in this deque
887 @SuppressWarnings("unchecked")
888 public Object[] toArray() {
889 final ReentrantLock lock = this.lock;
892 Object[] a = new Object[count];
894 for (Node<E> p = first; p != null; p = p.next)
903 * Returns an array containing all of the elements in this deque, in
904 * proper sequence; the runtime type of the returned array is that of
905 * the specified array. If the deque fits in the specified array, it
906 * is returned therein. Otherwise, a new array is allocated with the
907 * runtime type of the specified array and the size of this deque.
909 * <p>If this deque fits in the specified array with room to spare
910 * (i.e., the array has more elements than this deque), the element in
911 * the array immediately following the end of the deque is set to
914 * <p>Like the {@link #toArray()} method, this method acts as bridge between
915 * array-based and collection-based APIs. Further, this method allows
916 * precise control over the runtime type of the output array, and may,
917 * under certain circumstances, be used to save allocation costs.
919 * <p>Suppose {@code x} is a deque known to contain only strings.
920 * The following code can be used to dump the deque into a newly
921 * allocated array of {@code String}:
924 * String[] y = x.toArray(new String[0]);</pre>
926 * Note that {@code toArray(new Object[0])} is identical in function to
929 * @param a the array into which the elements of the deque are to
930 * be stored, if it is big enough; otherwise, a new array of the
931 * same runtime type is allocated for this purpose
932 * @return an array containing all of the elements in this deque
933 * @throws ArrayStoreException if the runtime type of the specified array
934 * is not a supertype of the runtime type of every element in
936 * @throws NullPointerException if the specified array is null
938 @SuppressWarnings("unchecked")
939 public <T> T[] toArray(T[] a) {
940 final ReentrantLock lock = this.lock;
943 if (a.length < count)
944 a = (T[])java.lang.reflect.Array.newInstance
945 (a.getClass().getComponentType(), count);
948 for (Node<E> p = first; p != null; p = p.next)
958 public String toString() {
959 final ReentrantLock lock = this.lock;
966 StringBuilder sb = new StringBuilder();
970 sb.append(e == this ? "(this Collection)" : e);
973 return sb.append(']').toString();
974 sb.append(',').append(' ');
982 * Atomically removes all of the elements from this deque.
983 * The deque will be empty after this call returns.
985 public void clear() {
986 final ReentrantLock lock = this.lock;
989 for (Node<E> f = first; f != null; ) {
1005 * Returns an iterator over the elements in this deque in proper sequence.
1006 * The elements will be returned in order from first (head) to last (tail).
1008 * <p>The returned iterator is a "weakly consistent" iterator that
1009 * will never throw {@link java.util.ConcurrentModificationException
1010 * ConcurrentModificationException}, and guarantees to traverse
1011 * elements as they existed upon construction of the iterator, and
1012 * may (but is not guaranteed to) reflect any modifications
1013 * subsequent to construction.
1015 * @return an iterator over the elements in this deque in proper sequence
1017 public Iterator<E> iterator() {
1022 * Returns an iterator over the elements in this deque in reverse
1023 * sequential order. The elements will be returned in order from
1024 * last (tail) to first (head).
1026 * <p>The returned iterator is a "weakly consistent" iterator that
1027 * will never throw {@link java.util.ConcurrentModificationException
1028 * ConcurrentModificationException}, and guarantees to traverse
1029 * elements as they existed upon construction of the iterator, and
1030 * may (but is not guaranteed to) reflect any modifications
1031 * subsequent to construction.
1033 * @return an iterator over the elements in this deque in reverse order
1035 public Iterator<E> descendingIterator() {
1036 return new DescendingItr();
1040 * Base class for Iterators for LinkedBlockingDeque
1042 private abstract class AbstractItr implements Iterator<E> {
1044 * The next node to return in next()
1049 * nextItem holds on to item fields because once we claim that
1050 * an element exists in hasNext(), we must return item read
1051 * under lock (in advance()) even if it was in the process of
1052 * being removed when hasNext() was called.
1057 * Node returned by most recent call to next. Needed by remove.
1058 * Reset to null if this element is deleted by a call to remove.
1060 private Node<E> lastRet;
1062 abstract Node<E> firstNode();
1063 abstract Node<E> nextNode(Node<E> n);
1066 // set to initial position
1067 final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1071 nextItem = (next == null) ? null : next.item;
1078 * Returns the successor node of the given non-null, but
1079 * possibly previously deleted, node.
1081 private Node<E> succ(Node<E> n) {
1082 // Chains of deleted nodes ending in null or self-links
1083 // are possible if multiple interior nodes are removed.
1085 Node<E> s = nextNode(n);
1088 else if (s.item != null)
1101 final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1104 // assert next != null;
1106 nextItem = (next == null) ? null : next.item;
1112 public boolean hasNext() {
1113 return next != null;
1118 throw new NoSuchElementException();
1125 public void remove() {
1126 Node<E> n = lastRet;
1128 throw new IllegalStateException();
1130 final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1141 /** Forward iterator */
1142 private class Itr extends AbstractItr {
1143 Node<E> firstNode() { return first; }
1144 Node<E> nextNode(Node<E> n) { return n.next; }
1147 /** Descending iterator */
1148 private class DescendingItr extends AbstractItr {
1149 Node<E> firstNode() { return last; }
1150 Node<E> nextNode(Node<E> n) { return n.prev; }
1154 * Save the state of this deque to a stream (that is, serialize it).
1156 * @serialData The capacity (int), followed by elements (each an
1157 * {@code Object}) in the proper order, followed by a null
1158 * @param s the stream
1160 private void writeObject(java.io.ObjectOutputStream s)
1161 throws java.io.IOException {
1162 final ReentrantLock lock = this.lock;
1165 // Write out capacity and any hidden stuff
1166 s.defaultWriteObject();
1167 // Write out all elements in the proper order.
1168 for (Node<E> p = first; p != null; p = p.next)
1169 s.writeObject(p.item);
1170 // Use trailing null as sentinel
1171 s.writeObject(null);
1178 * Reconstitute this deque from a stream (that is,
1180 * @param s the stream
1182 private void readObject(java.io.ObjectInputStream s)
1183 throws java.io.IOException, ClassNotFoundException {
1184 s.defaultReadObject();
1188 // Read in all elements and place in queue
1190 @SuppressWarnings("unchecked")
1191 E item = (E)s.readObject();