LinkedBlockingDeque 是基于链表实现的,可以选择有界或无界的双端阻塞队列。
*/
public class LinkedBlockingDeque
private static final long serialVersionUID = -387911632671998426L;
/** 双向链表节点 */
static final class Node
 /**
  * One of:
  * - the real predecessor Node
  * - this Node, meaning the predecessor is tail
  * - null, meaning there is no predecessor
  */
 Node<E> prev;
 /**
  * One of:
  * - the real successor Node
  * - this Node, meaning the successor is head
  * - null, meaning there is no successor
  */
 Node<E> next;
 Node(E x) {
     item = x;
 }
}
/**
/**
/** 双端队列中的元素总数 */
private transient int count;
/** 双端队列的容量 */
private final int capacity;
/** 控制访问的锁 */
final ReentrantLock lock = new ReentrantLock();
/** 队列为空时,用于阻塞执行 take 操作的线程的非空条件 */
private final Condition notEmpty = lock.newCondition();
/** 队列已满时,用于阻塞执行 put 操作的线程的非满条件 */
private final Condition notFull = lock.newCondition();
/**
- 创建一个容量为 Integer.MAX_VALUE 的双端阻塞队列
 */
 public LinkedBlockingDeque() {
 this(Integer.MAX_VALUE);
 }
/**
- 创建一个容量为 capacity 的双端阻塞队列
 */
 public LinkedBlockingDeque(int capacity) {
 if (capacity <= 0) {
 throw new IllegalArgumentException();
 }
 this.capacity = capacity;
 }
/**
- Creates a {@code LinkedBlockingDeque} with a capacity of
- {@link Integer#MAX_VALUE}, initially containing the elements of
- the given collection, added in traversal order of the
- collection‘s iterator.
- @param c the collection of elements to initially contain
- @throws NullPointerException if the specified collection or any
-     of its elements are null
 */
 public LinkedBlockingDeque(Collection<? extends E> c) {
 this(Integer.MAX_VALUE);
 addAll(c);
 }
private boolean linkFirst(Node
private boolean linkLast(Node
/**
- Removes and returns first element, or null if empty.
 */
 private E unlinkFirst() {
 // assert lock.isHeldByCurrentThread();
 final Node
/**
- Removes and returns last element, or null if empty.
 */
 private E unlinkLast() {
 // assert lock.isHeldByCurrentThread();
 final Node
/**
- Unlinks x.
 */
 void unlink(Node
// BlockingDeque methods
/**
- @throws IllegalStateException if this deque is full
- @throws NullPointerException {@inheritDoc}
 */
 @Override
 public void addFirst(E e) {
 if (!offerFirst(e)) {
 throw new IllegalStateException("Deque full");
 }
 }
/**
- @throws IllegalStateException if this deque is full
- @throws NullPointerException {@inheritDoc}
 */
 @Override
 public void addLast(E e) {
 if (!offerLast(e)) {
 throw new IllegalStateException("Deque full");
 }
 }
/**
- 如果队列已满,则直接返回 false,否则将目标元素 e 添加到队列头部
 */
 @Override
 public boolean offerFirst(E e) {
 if (e == null) {
 throw new NullPointerException();
 }
 final Node
/**
- 如果队列已满,则直接返回 false,否则将目标元素 e 添加到队列尾部
 */
 @Override
 public boolean offerLast(E e) {
 if (e == null) {
 throw new NullPointerException();
 }
 final Node
/**
- 将目标元素 e 添加到队列头部,如果队列已满,则阻塞等待有可用空间后重试
 */
 @Override
 public void putFirst(E e) throws InterruptedException {
 if (e == null) {
 throw new NullPointerException();
 }
 final Node
/**
- 将目标元素 e 添加到队列尾部,如果队列已满,则阻塞等待有可用空间后重试
 */
 @Override
 public void putLast(E e) throws InterruptedException {
 if (e == null) {
 throw new NullPointerException();
 }
 final Node
/**
- 在指定的超时时间内尝试将目标元素 e 添加到队列头部,成功则返回 true
 */
 @Override
 public boolean offerFirst(E e, long timeout, TimeUnit unit)
 throws InterruptedException {
 if (e == null) {
 throw new NullPointerException();
 }
 final Node
/**
- 在指定的超时时间内尝试将目标元素 e 添加到队列尾部,成功则返回 true
 */
 @Override
 public boolean offerLast(E e, long timeout, TimeUnit unit)
 throws InterruptedException {
 if (e == null) {
 throw new NullPointerException();
 }
 final Node
/**
- @throws NoSuchElementException {@inheritDoc}
 */
 @Override
 public E removeFirst() {
 final E x = pollFirst();
 if (x == null) {
 throw new NoSuchElementException();
 }
 return x;
 }
/**
- @throws NoSuchElementException {@inheritDoc}
 */
 @Override
 public E removeLast() {
 final E x = pollLast();
 if (x == null) {
 throw new NoSuchElementException();
 }
 return x;
 }
/**
- 如果队列为空,则立即返回 null,否则移除并返回头部元素
- created by ZXD at 6 Dec 2018 T 21:03:40
- @return
 */
 @Override
 public E pollFirst() {
 final ReentrantLock lock = this.lock;
 lock.lock();
 try {
 return unlinkFirst();
 } finally {
 lock.unlock();
 }
 }
/**
- 如果队列为空,则立即返回 null,否则移除并返回尾部元素
- created by ZXD at 6 Dec 2018 T 21:04:43
- @return
 */
 @Override
 public E pollLast() {
 final ReentrantLock lock = this.lock;
 lock.lock();
 try {
 return unlinkLast();
 } finally {
 lock.unlock();
 }
 }
/**
- 移除并返回头部节点,如果队列为空,则阻塞等待有可用元素之后重试
- created by ZXD at 6 Dec 2018 T 21:00:25
- @return
- @throws InterruptedException
 */
 @Override
 public E takeFirst() throws InterruptedException {
 final ReentrantLock lock = this.lock;
 lock.lock();
 try {
 E x;
 // 尝试移除并返回头部节点
 while ( (x = unlinkFirst()) == null) {
 // 队列为空,则阻塞等待有可用元素之后重试
 notEmpty.await();
 }
 return x;
 } finally {
 lock.unlock();
 }
 }
/**
- 移除并返回尾部节点,如果队列为空,则阻塞等待有可用元素之后重试
- created by ZXD at 6 Dec 2018 T 21:02:04
- @return
- @throws InterruptedException
 */
 @Override
 public E takeLast() throws InterruptedException {
 final ReentrantLock lock = this.lock;
 lock.lock();
 try {
 E x;
 // 尝试移除并返回尾部节点
 while ( (x = unlinkLast()) == null) {
 // 队列为空,则阻塞等待有可用元素之后重试
 notEmpty.await();
 }
 return x;
 } finally {
 lock.unlock();
 }
 }
/**
- 在指定的超时时间内尝试移除并返回头部元素,如果已经超时,则返回 null
- created by ZXD at 6 Dec 2018 T 21:05:21
- @param timeout
- @param unit
- @return
- @throws InterruptedException
 */
 @Override
 public E pollFirst(long timeout, TimeUnit unit)
 throws InterruptedException {
 long nanos = unit.toNanos(timeout);
 final ReentrantLock lock = this.lock;
 lock.lockInterruptibly();
 try {
 E x;
 // 尝试移除并返回头部元素
 while ( (x = unlinkFirst()) == null) {
 // 已经超时则返回 null
 if (nanos <= 0L) {
 return null;
 }
 // 当前线程在非空条件上阻塞等待,被唤醒后进行重试
 nanos = notEmpty.awaitNanos(nanos);
 }
 // 移除成功则直接返回头部元素
 return x;
 } finally {
 lock.unlock();
 }
 }
/**
- created by ZXD at 6 Dec 2018 T 21:08:24
- @param timeout
- @param unit
- @return
- @throws InterruptedException
 */
 @Override
 public E pollLast(long timeout, TimeUnit unit)
 throws InterruptedException {
 long nanos = unit.toNanos(timeout);
 final ReentrantLock lock = this.lock;
 lock.lockInterruptibly();
 try {
 E x;
 // 尝试移除并返回尾部元素
 while ( (x = unlinkLast()) == null) {
 // 已经超时则返回 null
 if (nanos <= 0L) {
 return null;
 }
 // 当前线程在非空条件上阻塞等待,被唤醒后进行重试
 nanos = notEmpty.awaitNanos(nanos);
 }
 // 移除成功则直接返回尾部元素
 return x;
 } finally {
 lock.unlock();
 }
 }
/**
- @throws NoSuchElementException {@inheritDoc}
 */
 @Override
 public E getFirst() {
 final E x = peekFirst();
 if (x == null) {
 throw new NoSuchElementException();
 }
 return x;
 }
/**
- @throws NoSuchElementException {@inheritDoc}
 */
 @Override
 public E getLast() {
 final E x = peekLast();
 if (x == null) {
 throw new NoSuchElementException();
 }
 return x;
 }
@Override
public E peekFirst() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return first == null ? null : first.item;
} finally {
lock.unlock();
}
}
@Override
public E peekLast() {
final ReentrantLock lock = this.lock;
lock.lock();
try {
return last == null ? null : last.item;
} finally {
lock.unlock();
}
}
@Override
public boolean removeFirstOccurrence(Object o) {
if (o == null) {
return false;
}
final ReentrantLock lock = this.lock;
lock.lock();
try {
for (Node
@Override
public boolean removeLastOccurrence(Object o) {
if (o == null) {
return false;
}
final ReentrantLock lock = this.lock;
lock.lock();
try {
for (Node
// BlockingQueue methods
/**
/**
- @throws NullPointerException if the specified element is null
 */
 @Override
 public boolean offer(E e) {
 return offerLast(e);
 }
/**
- @throws NullPointerException {@inheritDoc}
- @throws InterruptedException {@inheritDoc}
 */
 @Override
 public void put(E e) throws InterruptedException {
 putLast(e);
 }
/**
- @throws NullPointerException {@inheritDoc}
- @throws InterruptedException {@inheritDoc}
 */
 @Override
 public boolean offer(E e, long timeout, TimeUnit unit)
 throws InterruptedException {
 return offerLast(e, timeout, unit);
 }
/**@Override
public E poll() {
return pollFirst();
}
@Override
public E take() throws InterruptedException {
return takeFirst();
}
@Override
public E poll(long timeout, TimeUnit unit) throws InterruptedException {
return pollFirst(timeout, unit);
}
/**
@Override
public E peek() {
return peekFirst();
}
/**
/**
- @throws UnsupportedOperationException {@inheritDoc}
- @throws ClassCastException {@inheritDoc}
- @throws NullPointerException {@inheritDoc}
- @throws IllegalArgumentException {@inheritDoc}
 */
 @Override
 public int drainTo(Collection<? super E> c) {
 return drainTo(c, Integer.MAX_VALUE);
 }
/**
- @throws UnsupportedOperationException {@inheritDoc}
- @throws ClassCastException {@inheritDoc}
- @throws NullPointerException {@inheritDoc}
- @throws IllegalArgumentException {@inheritDoc}
 */
 @Override
 public int drainTo(Collection<? super E> c, int maxElements) {
 Objects.requireNonNull(c);
 if (c == this) {
 throw new IllegalArgumentException();
 }
 if (maxElements <= 0) {
 return 0;
 }
 final ReentrantLock lock = this.lock;
 lock.lock();
 try {
 final int n = Math.min(maxElements, count);
 for (int i = 0; i < n; i++) {
 c.add(first.item); // In this order, in case add() throws.
 unlinkFirst();
 }
 return n;
 } finally {
 lock.unlock();
 }
 }
// Stack methods
/**
- @throws IllegalStateException if this deque is full
- @throws NullPointerException {@inheritDoc}
 */
 @Override
 public void push(E e) {
 addFirst(e);
 }
/**
- @throws NoSuchElementException {@inheritDoc}
 */
 @Override
 public E pop() {
 return removeFirst();
 }
// Collection methods
/**
/**
- Returns the number of elements in this deque.
- @return the number of elements in this deque
 */
 @Override
 public int size() {
 final ReentrantLock lock = this.lock;
 lock.lock();
 try {
 return count;
 } finally {
 lock.unlock();
 }
 }
/**
- Returns {@code true} if this deque contains the specified element.
- More formally, returns {@code true} if and only if this deque contains
- at least one element {@code e} such that {@code o.equals(e)}.
- @param o object to be checked for containment in this deque
- @return {@code true} if this deque contains the specified element
 */
 @Override
 public boolean contains(Object o) {
 if (o == null) {
 return false;
 }
 final ReentrantLock lock = this.lock;
 lock.lock();
 try {
 for (Node
/**
- Appends all of the elements in the specified collection to the end of
- this deque, in the order that they are returned by the specified
- collection‘s iterator. Attempts to {@code addAll} of a deque to
- itself result in {@code IllegalArgumentException}.
- @param c the elements to be inserted into this deque
- @return {@code true} if this deque changed as a result of the call
- @throws NullPointerException if the specified collection or any
-     of its elements are null
 
- @throws IllegalArgumentException if the collection is this deque
- @throws IllegalStateException if this deque is full
- @see #add(Object)
 */
 @Override
 public boolean addAll(Collection<? extends E> c) {
 if (c == this) {
 // As historically specified in AbstractQueue#addAll
 throw new IllegalArgumentException();
 }
 - // Copy c into a private chain of Nodes
 Node
 - // Atomically append the chain at the end
 final ReentrantLock lock = this.lock;
 lock.lock();
 try {
 if (count + n <= capacity) {
 beg.prev = last;
 if (first == null) {
 first = beg;
 } else {
 last.next = beg;
 }
 last = end;
 count += n;
 notEmpty.signalAll();
 return true;
 }
 } finally {
 lock.unlock();
 }
 // Fall back to historic non-atomic implementation, failing
 // with IllegalStateException when the capacity is exceeded.
 return super.addAll(c);
 }
 
/**
/**
- Returns an array containing all of the elements in this deque, in
- proper sequence; the runtime type of the returned array is that of
- the specified array. If the deque fits in the specified array, it
- is returned therein. Otherwise, a new array is allocated with the
- runtime type of the specified array and the size of this deque.
- 
If this deque fits in the specified array with room to spare 
- (i.e., the array has more elements than this deque), the element in
- the array immediately following the end of the deque is set to
- {@code null}.
- 
Like the {@link #toArray()} method, this method acts as bridge between 
- array-based and collection-based APIs. Further, this method allows
- precise control over the runtime type of the output array, and may,
- under certain circumstances, be used to save allocation costs.
- 
Suppose {@code x} is a deque known to contain only strings. 
- The following code can be used to dump the deque into a newly
- allocated array of {@code String}:
-  {@code String[] y = x.toArray(new String[0]);}
- Note that {@code toArray(new Object[0])} is identical in function to
- {@code toArray()}.
- @param a the array into which the elements of the deque are to
-      be stored, if it is big enough; otherwise, a new array of the
 
-      same runtime type is allocated for this purpose
 
- @return an array containing all of the elements in this deque
- @throws ArrayStoreException if the runtime type of the specified array
-     is not a supertype of the runtime type of every element in
 
-     this deque
 
- @throws NullPointerException if the specified array is null
 */
 @Override
 @SuppressWarnings("unchecked")
 public
 -  int k = 0;
 for (Node<E> p = first; p != null; p = p.next) {
     a[k++] = (T)p.item;
 }
 if (a.length > k) {
     a[k] = null;
 }
 return a;
 - } finally {
 lock.unlock();
 }
 }
 
@Override
public String toString() {
return Helpers.collectionToString(this);
}
/**
- Atomically removes all of the elements from this deque.
- The deque will be empty after this call returns.
 */
 @Override
 public void clear() {
 final ReentrantLock lock = this.lock;
 lock.lock();
 try {
 for (Node
/**
- Used for any element traversal that is not entirely under lock.
- Such traversals must handle both:
- 
- dequeued nodes (p.next == p)
 
- 
- (possibly multiple) interior removed nodes (p.item == null)
 */
 Node
 
/**
- Returns an iterator over the elements in this deque in proper sequence.
- The elements will be returned in order from first (head) to last (tail).
- 
The returned iterator is 
- weakly consistent.
- @return an iterator over the elements in this deque in proper sequence
 */
 @Override
 public Iterator
/**
- Returns an iterator over the elements in this deque in reverse
- sequential order. The elements will be returned in order from
- last (tail) to first (head).
- 
The returned iterator is 
- weakly consistent.
- @return an iterator over the elements in this deque in reverse order
 */
 @Override
 public Iterator
/**
- Base class for LinkedBlockingDeque iterators.
 */
 private abstract class AbstractItr implements Iterator
/** Forward iterator */
private class Itr extends AbstractItr {
Itr() {} // prevent access constructor creation
@Override
Node
/** Descending iterator */
private class DescendingItr extends AbstractItr {
DescendingItr() {} // prevent access constructor creation
@Override
Node
/**
- A customized variant of Spliterators.IteratorSpliterator.
- Keep this class in sync with (very similar) LBQSpliterator.
 */
 private final class LBDSpliterator implements Spliterator
 - LBDSpliterator() {} - @Override
 public long estimateSize() { return est; }
 - @Override
 public Spliterator
 - @Override
 public boolean tryAdvance(Consumer<? super E> action) {
 Objects.requireNonNull(action);
 if (!exhausted) {
 E e = null;
 final ReentrantLock lock = LinkedBlockingDeque.this.lock;
 lock.lock();
 try {
 Node
 - @Override
 public void forEachRemaining(Consumer<? super E> action) {
 Objects.requireNonNull(action);
 if (!exhausted) {
 exhausted = true;
 final Node
 - @Override
 public int characteristics() {
 return Spliterator.ORDERED |
 Spliterator.NONNULL |
 Spliterator.CONCURRENT;
 }
 }
 
/**
/**
- @throws NullPointerException {@inheritDoc}
 */
 @Override
 public void forEach(Consumer<? super E> action) {
 Objects.requireNonNull(action);
 forEachFrom(action, null);
 }
/**
- Runs action on each element found during a traversal starting at p.
- If p is null, traversal starts at head.
 */
 void forEachFrom(Consumer<? super E> action, Node
/**
- @throws NullPointerException {@inheritDoc}
 */
 @Override
 public boolean removeIf(Predicate<? super E> filter) {
 Objects.requireNonNull(filter);
 return bulkRemove(filter);
 }
/**
- @throws NullPointerException {@inheritDoc}
 */
 @Override
 public boolean removeAll(Collection<?> c) {
 Objects.requireNonNull(c);
 return bulkRemove(e -> c.contains(e));
 }
/**
- @throws NullPointerException {@inheritDoc}
 */
 @Override
 public boolean retainAll(Collection<?> c) {
 Objects.requireNonNull(c);
 return bulkRemove(e -> !c.contains(e));
 }
/** Implementation of bulk remove methods. */
@SuppressWarnings("unchecked")
private boolean bulkRemove(Predicate<? super E> filter) {
boolean removed = false;
Node
     // 2. Run the filter on the elements while lock is free.
     for (int i = 0; i < n; i++) {
         final E e;
         if ((e = nodes[i].item) != null && filter.test(e)) {
             deathRow |= 1L << i;
         }
     }
     // 3. Remove any filtered elements while holding the lock.
     if (deathRow != 0) {
         lock.lock();
         try {
             for (int i = 0; i < n; i++) {
                 final Node<E> q;
                 if ((deathRow & 1L << i) != 0L
                         && (q = nodes[i]).item != null) {
                     unlink(q);
                     removed = true;
                 }
             }
         } finally {
             lock.unlock();
         }
     }
 } while (n > 0 && p != null);
 return removed;
}
/**
- Saves this deque to a stream (that is, serializes it).
- @param s the stream
- @throws java.io.IOException if an I/O error occurs
- @serialData The capacity (int), followed by elements (each an
- {@code Object}) in the proper order, followed by a null
 */
 private void writeObject(java.io.ObjectOutputStream s)
 throws java.io.IOException {
 final ReentrantLock lock = this.lock;
 lock.lock();
 try {
 // Write out capacity and any hidden stuff
 s.defaultWriteObject();
 // Write out all elements in the proper order.
 for (Node
/**
- Reconstitutes this deque from a stream (that is, deserializes it).
- @param s the stream
- @throws ClassNotFoundException if the class of a serialized object
-     could not be found
 
- @throws java.io.IOException if an I/O error occurs
 */
 private void readObject(java.io.ObjectInputStream s)
 throws java.io.IOException, ClassNotFoundException {
 s.defaultReadObject();
 count = 0;
 first = null;
 last = null;
 // Read in all elements and place in queue
 for (;;) {
 @SuppressWarnings("unchecked")
 final E item = (E)s.readObject();
 if (item == null) {
 break;
 }
 add(item);
 }
 }
void checkInvariants() {
// assert lock.isHeldByCurrentThread();
// Nodes may get self-linked or lose their item, but only
// after being unlinked and becoming unreachable from first.
for (Node