0N/A/*
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/A/*
0N/A * This file is available under and governed by the GNU General Public
0N/A * License version 2 only, as published by the Free Software Foundation.
0N/A * However, the following notice accompanied the original version of this
0N/A * file:
0N/A *
0N/A * Written by Doug Lea with assistance from members of JCP JSR-166
0N/A * Expert Group and released to the public domain, as explained at
3984N/A * http://creativecommons.org/publicdomain/zero/1.0/
0N/A */
0N/A
0N/Apackage java.util.concurrent;
1468N/A
1468N/Aimport java.util.AbstractQueue;
1468N/Aimport java.util.Collection;
1468N/Aimport java.util.Iterator;
1468N/Aimport java.util.NoSuchElementException;
1468N/Aimport java.util.concurrent.locks.Condition;
1468N/Aimport java.util.concurrent.locks.ReentrantLock;
0N/A
0N/A/**
0N/A * An optionally-bounded {@linkplain BlockingDeque blocking deque} based on
0N/A * linked nodes.
0N/A *
0N/A * <p> The optional capacity bound constructor argument serves as a
0N/A * way to prevent excessive expansion. The capacity, if unspecified,
0N/A * is equal to {@link Integer#MAX_VALUE}. Linked nodes are
0N/A * dynamically created upon each insertion unless this would bring the
0N/A * deque above capacity.
0N/A *
0N/A * <p>Most operations run in constant time (ignoring time spent
0N/A * blocking). Exceptions include {@link #remove(Object) remove},
0N/A * {@link #removeFirstOccurrence removeFirstOccurrence}, {@link
0N/A * #removeLastOccurrence removeLastOccurrence}, {@link #contains
0N/A * contains}, {@link #iterator iterator.remove()}, and the bulk
0N/A * operations, all of which run in linear time.
0N/A *
0N/A * <p>This class and its iterator implement all of the
0N/A * <em>optional</em> methods of the {@link Collection} and {@link
0N/A * Iterator} interfaces.
0N/A *
0N/A * <p>This class is a member of the
0N/A * <a href="{@docRoot}/../technotes/guides/collections/index.html">
0N/A * Java Collections Framework</a>.
0N/A *
0N/A * @since 1.6
0N/A * @author Doug Lea
0N/A * @param <E> the type of elements held in this collection
0N/A */
0N/Apublic class LinkedBlockingDeque<E>
0N/A extends AbstractQueue<E>
0N/A implements BlockingDeque<E>, java.io.Serializable {
0N/A
0N/A /*
0N/A * Implemented as a simple doubly-linked list protected by a
0N/A * single lock and using conditions to manage blocking.
1468N/A *
1468N/A * To implement weakly consistent iterators, it appears we need to
1468N/A * keep all Nodes GC-reachable from a predecessor dequeued Node.
1468N/A * That would cause two problems:
1468N/A * - allow a rogue Iterator to cause unbounded memory retention
1468N/A * - cause cross-generational linking of old Nodes to new Nodes if
1468N/A * a Node was tenured while live, which generational GCs have a
1468N/A * hard time dealing with, causing repeated major collections.
1468N/A * However, only non-deleted Nodes need to be reachable from
1468N/A * dequeued Nodes, and reachability does not necessarily have to
1468N/A * be of the kind understood by the GC. We use the trick of
1468N/A * linking a Node that has just been dequeued to itself. Such a
1468N/A * self-link implicitly means to jump to "first" (for next links)
1468N/A * or "last" (for prev links).
0N/A */
0N/A
0N/A /*
0N/A * We have "diamond" multiple interface/abstract class inheritance
0N/A * here, and that introduces ambiguities. Often we want the
0N/A * BlockingDeque javadoc combined with the AbstractQueue
0N/A * implementation, so a lot of method specs are duplicated here.
0N/A */
0N/A
0N/A private static final long serialVersionUID = -387911632671998426L;
0N/A
0N/A /** Doubly-linked list node class */
0N/A static final class Node<E> {
1468N/A /**
1468N/A * The item, or null if this node has been removed.
1468N/A */
0N/A E item;
1468N/A
1468N/A /**
1468N/A * One of:
1468N/A * - the real predecessor Node
1468N/A * - this Node, meaning the predecessor is tail
1468N/A * - null, meaning there is no predecessor
1468N/A */
0N/A Node<E> prev;
1468N/A
1468N/A /**
1468N/A * One of:
1468N/A * - the real successor Node
1468N/A * - this Node, meaning the successor is head
1468N/A * - null, meaning there is no successor
1468N/A */
0N/A Node<E> next;
1468N/A
3059N/A Node(E x) {
0N/A item = x;
0N/A }
0N/A }
0N/A
1468N/A /**
1468N/A * Pointer to first node.
1468N/A * Invariant: (first == null && last == null) ||
1468N/A * (first.prev == null && first.item != null)
1468N/A */
1468N/A transient Node<E> first;
1468N/A
1468N/A /**
1468N/A * Pointer to last node.
1468N/A * Invariant: (first == null && last == null) ||
1468N/A * (last.next == null && last.item != null)
1468N/A */
1468N/A transient Node<E> last;
1468N/A
0N/A /** Number of items in the deque */
0N/A private transient int count;
1468N/A
0N/A /** Maximum number of items in the deque */
0N/A private final int capacity;
1468N/A
0N/A /** Main lock guarding all access */
1468N/A final ReentrantLock lock = new ReentrantLock();
1468N/A
0N/A /** Condition for waiting takes */
0N/A private final Condition notEmpty = lock.newCondition();
1468N/A
0N/A /** Condition for waiting puts */
0N/A private final Condition notFull = lock.newCondition();
0N/A
0N/A /**
1468N/A * Creates a {@code LinkedBlockingDeque} with a capacity of
0N/A * {@link Integer#MAX_VALUE}.
0N/A */
0N/A public LinkedBlockingDeque() {
0N/A this(Integer.MAX_VALUE);
0N/A }
0N/A
0N/A /**
1468N/A * Creates a {@code LinkedBlockingDeque} with the given (fixed) capacity.
0N/A *
0N/A * @param capacity the capacity of this deque
1468N/A * @throws IllegalArgumentException if {@code capacity} is less than 1
0N/A */
0N/A public LinkedBlockingDeque(int capacity) {
0N/A if (capacity <= 0) throw new IllegalArgumentException();
0N/A this.capacity = capacity;
0N/A }
0N/A
0N/A /**
1468N/A * Creates a {@code LinkedBlockingDeque} with a capacity of
0N/A * {@link Integer#MAX_VALUE}, initially containing the elements of
0N/A * the given collection, added in traversal order of the
0N/A * collection's iterator.
0N/A *
0N/A * @param c the collection of elements to initially contain
0N/A * @throws NullPointerException if the specified collection or any
0N/A * of its elements are null
0N/A */
0N/A public LinkedBlockingDeque(Collection<? extends E> c) {
0N/A this(Integer.MAX_VALUE);
1468N/A final ReentrantLock lock = this.lock;
1468N/A lock.lock(); // Never contended, but necessary for visibility
1468N/A try {
1468N/A for (E e : c) {
1468N/A if (e == null)
1468N/A throw new NullPointerException();
3059N/A if (!linkLast(new Node<E>(e)))
1468N/A throw new IllegalStateException("Deque full");
1468N/A }
1468N/A } finally {
1468N/A lock.unlock();
1468N/A }
0N/A }
0N/A
0N/A
0N/A // Basic linking and unlinking operations, called only while holding lock
0N/A
0N/A /**
3059N/A * Links node as first element, or returns false if full.
0N/A */
3059N/A private boolean linkFirst(Node<E> node) {
1468N/A // assert lock.isHeldByCurrentThread();
0N/A if (count >= capacity)
0N/A return false;
0N/A Node<E> f = first;
3059N/A node.next = f;
3059N/A first = node;
0N/A if (last == null)
3059N/A last = node;
0N/A else
3059N/A f.prev = node;
1468N/A ++count;
0N/A notEmpty.signal();
0N/A return true;
0N/A }
0N/A
0N/A /**
3059N/A * Links node as last element, or returns false if full.
0N/A */
3059N/A private boolean linkLast(Node<E> node) {
1468N/A // assert lock.isHeldByCurrentThread();
0N/A if (count >= capacity)
0N/A return false;
0N/A Node<E> l = last;
3059N/A node.prev = l;
3059N/A last = node;
0N/A if (first == null)
3059N/A first = node;
0N/A else
3059N/A l.next = node;
1468N/A ++count;
0N/A notEmpty.signal();
0N/A return true;
0N/A }
0N/A
0N/A /**
0N/A * Removes and returns first element, or null if empty.
0N/A */
0N/A private E unlinkFirst() {
1468N/A // assert lock.isHeldByCurrentThread();
0N/A Node<E> f = first;
0N/A if (f == null)
0N/A return null;
0N/A Node<E> n = f.next;
1468N/A E item = f.item;
1468N/A f.item = null;
1468N/A f.next = f; // help GC
0N/A first = n;
0N/A if (n == null)
0N/A last = null;
0N/A else
0N/A n.prev = null;
0N/A --count;
0N/A notFull.signal();
1468N/A return item;
0N/A }
0N/A
0N/A /**
0N/A * Removes and returns last element, or null if empty.
0N/A */
0N/A private E unlinkLast() {
1468N/A // assert lock.isHeldByCurrentThread();
0N/A Node<E> l = last;
0N/A if (l == null)
0N/A return null;
0N/A Node<E> p = l.prev;
1468N/A E item = l.item;
1468N/A l.item = null;
1468N/A l.prev = l; // help GC
0N/A last = p;
0N/A if (p == null)
0N/A first = null;
0N/A else
0N/A p.next = null;
0N/A --count;
0N/A notFull.signal();
1468N/A return item;
0N/A }
0N/A
0N/A /**
1468N/A * Unlinks x.
0N/A */
1468N/A void unlink(Node<E> x) {
1468N/A // assert lock.isHeldByCurrentThread();
0N/A Node<E> p = x.prev;
0N/A Node<E> n = x.next;
0N/A if (p == null) {
1468N/A unlinkFirst();
0N/A } else if (n == null) {
1468N/A unlinkLast();
0N/A } else {
0N/A p.next = n;
0N/A n.prev = p;
1468N/A x.item = null;
1468N/A // Don't mess with x's links. They may still be in use by
1468N/A // an iterator.
1468N/A --count;
1468N/A notFull.signal();
0N/A }
0N/A }
0N/A
0N/A // BlockingDeque methods
0N/A
0N/A /**
0N/A * @throws IllegalStateException {@inheritDoc}
0N/A * @throws NullPointerException {@inheritDoc}
0N/A */
0N/A public void addFirst(E e) {
0N/A if (!offerFirst(e))
0N/A throw new IllegalStateException("Deque full");
0N/A }
0N/A
0N/A /**
0N/A * @throws IllegalStateException {@inheritDoc}
0N/A * @throws NullPointerException {@inheritDoc}
0N/A */
0N/A public void addLast(E e) {
0N/A if (!offerLast(e))
0N/A throw new IllegalStateException("Deque full");
0N/A }
0N/A
0N/A /**
0N/A * @throws NullPointerException {@inheritDoc}
0N/A */
0N/A public boolean offerFirst(E e) {
0N/A if (e == null) throw new NullPointerException();
3059N/A Node<E> node = new Node<E>(e);
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3059N/A return linkFirst(node);
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @throws NullPointerException {@inheritDoc}
0N/A */
0N/A public boolean offerLast(E e) {
0N/A if (e == null) throw new NullPointerException();
3059N/A Node<E> node = new Node<E>(e);
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3059N/A return linkLast(node);
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @throws NullPointerException {@inheritDoc}
0N/A * @throws InterruptedException {@inheritDoc}
0N/A */
0N/A public void putFirst(E e) throws InterruptedException {
0N/A if (e == null) throw new NullPointerException();
3059N/A Node<E> node = new Node<E>(e);
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3059N/A while (!linkFirst(node))
0N/A notFull.await();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @throws NullPointerException {@inheritDoc}
0N/A * @throws InterruptedException {@inheritDoc}
0N/A */
0N/A public void putLast(E e) throws InterruptedException {
0N/A if (e == null) throw new NullPointerException();
3059N/A Node<E> node = new Node<E>(e);
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3059N/A while (!linkLast(node))
0N/A notFull.await();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @throws NullPointerException {@inheritDoc}
0N/A * @throws InterruptedException {@inheritDoc}
0N/A */
0N/A public boolean offerFirst(E e, long timeout, TimeUnit unit)
0N/A throws InterruptedException {
0N/A if (e == null) throw new NullPointerException();
3059N/A Node<E> node = new Node<E>(e);
0N/A long nanos = unit.toNanos(timeout);
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lockInterruptibly();
0N/A try {
3059N/A while (!linkFirst(node)) {
0N/A if (nanos <= 0)
0N/A return false;
0N/A nanos = notFull.awaitNanos(nanos);
0N/A }
1468N/A return true;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @throws NullPointerException {@inheritDoc}
0N/A * @throws InterruptedException {@inheritDoc}
0N/A */
0N/A public boolean offerLast(E e, long timeout, TimeUnit unit)
0N/A throws InterruptedException {
0N/A if (e == null) throw new NullPointerException();
3059N/A Node<E> node = new Node<E>(e);
0N/A long nanos = unit.toNanos(timeout);
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lockInterruptibly();
0N/A try {
3059N/A while (!linkLast(node)) {
0N/A if (nanos <= 0)
0N/A return false;
0N/A nanos = notFull.awaitNanos(nanos);
0N/A }
1468N/A return true;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @throws NoSuchElementException {@inheritDoc}
0N/A */
0N/A public E removeFirst() {
0N/A E x = pollFirst();
0N/A if (x == null) throw new NoSuchElementException();
0N/A return x;
0N/A }
0N/A
0N/A /**
0N/A * @throws NoSuchElementException {@inheritDoc}
0N/A */
0N/A public E removeLast() {
0N/A E x = pollLast();
0N/A if (x == null) throw new NoSuchElementException();
0N/A return x;
0N/A }
0N/A
0N/A public E pollFirst() {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return unlinkFirst();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public E pollLast() {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return unlinkLast();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public E takeFirst() throws InterruptedException {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A E x;
0N/A while ( (x = unlinkFirst()) == null)
0N/A notEmpty.await();
0N/A return x;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public E takeLast() throws InterruptedException {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A E x;
0N/A while ( (x = unlinkLast()) == null)
0N/A notEmpty.await();
0N/A return x;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public E pollFirst(long timeout, TimeUnit unit)
0N/A throws InterruptedException {
0N/A long nanos = unit.toNanos(timeout);
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lockInterruptibly();
0N/A try {
1468N/A E x;
1468N/A while ( (x = unlinkFirst()) == null) {
0N/A if (nanos <= 0)
0N/A return null;
0N/A nanos = notEmpty.awaitNanos(nanos);
0N/A }
1468N/A return x;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public E pollLast(long timeout, TimeUnit unit)
0N/A throws InterruptedException {
0N/A long nanos = unit.toNanos(timeout);
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lockInterruptibly();
0N/A try {
1468N/A E x;
1468N/A while ( (x = unlinkLast()) == null) {
0N/A if (nanos <= 0)
0N/A return null;
0N/A nanos = notEmpty.awaitNanos(nanos);
0N/A }
1468N/A return x;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @throws NoSuchElementException {@inheritDoc}
0N/A */
0N/A public E getFirst() {
0N/A E x = peekFirst();
0N/A if (x == null) throw new NoSuchElementException();
0N/A return x;
0N/A }
0N/A
0N/A /**
0N/A * @throws NoSuchElementException {@inheritDoc}
0N/A */
0N/A public E getLast() {
0N/A E x = peekLast();
0N/A if (x == null) throw new NoSuchElementException();
0N/A return x;
0N/A }
0N/A
0N/A public E peekFirst() {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return (first == null) ? null : first.item;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public E peekLast() {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return (last == null) ? null : last.item;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public boolean removeFirstOccurrence(Object o) {
0N/A if (o == null) return false;
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A for (Node<E> p = first; p != null; p = p.next) {
0N/A if (o.equals(p.item)) {
0N/A unlink(p);
0N/A return true;
0N/A }
0N/A }
0N/A return false;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public boolean removeLastOccurrence(Object o) {
0N/A if (o == null) return false;
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A for (Node<E> p = last; p != null; p = p.prev) {
0N/A if (o.equals(p.item)) {
0N/A unlink(p);
0N/A return true;
0N/A }
0N/A }
0N/A return false;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A // BlockingQueue methods
0N/A
0N/A /**
0N/A * Inserts the specified element at the end of this deque unless it would
0N/A * violate capacity restrictions. When using a capacity-restricted deque,
0N/A * it is generally preferable to use method {@link #offer(Object) offer}.
0N/A *
0N/A * <p>This method is equivalent to {@link #addLast}.
0N/A *
0N/A * @throws IllegalStateException if the element cannot be added at this
0N/A * time due to capacity restrictions
0N/A * @throws NullPointerException if the specified element is null
0N/A */
0N/A public boolean add(E e) {
0N/A addLast(e);
0N/A return true;
0N/A }
0N/A
0N/A /**
0N/A * @throws NullPointerException if the specified element is null
0N/A */
0N/A public boolean offer(E e) {
0N/A return offerLast(e);
0N/A }
0N/A
0N/A /**
0N/A * @throws NullPointerException {@inheritDoc}
0N/A * @throws InterruptedException {@inheritDoc}
0N/A */
0N/A public void put(E e) throws InterruptedException {
0N/A putLast(e);
0N/A }
0N/A
0N/A /**
0N/A * @throws NullPointerException {@inheritDoc}
0N/A * @throws InterruptedException {@inheritDoc}
0N/A */
0N/A public boolean offer(E e, long timeout, TimeUnit unit)
0N/A throws InterruptedException {
0N/A return offerLast(e, timeout, unit);
0N/A }
0N/A
0N/A /**
0N/A * Retrieves and removes the head of the queue represented by this deque.
0N/A * This method differs from {@link #poll poll} only in that it throws an
0N/A * exception if this deque is empty.
0N/A *
0N/A * <p>This method is equivalent to {@link #removeFirst() removeFirst}.
0N/A *
0N/A * @return the head of the queue represented by this deque
0N/A * @throws NoSuchElementException if this deque is empty
0N/A */
0N/A public E remove() {
0N/A return removeFirst();
0N/A }
0N/A
0N/A public E poll() {
0N/A return pollFirst();
0N/A }
0N/A
0N/A public E take() throws InterruptedException {
0N/A return takeFirst();
0N/A }
0N/A
0N/A public E poll(long timeout, TimeUnit unit) throws InterruptedException {
0N/A return pollFirst(timeout, unit);
0N/A }
0N/A
0N/A /**
0N/A * Retrieves, but does not remove, the head of the queue represented by
0N/A * this deque. This method differs from {@link #peek peek} only in that
0N/A * it throws an exception if this deque is empty.
0N/A *
0N/A * <p>This method is equivalent to {@link #getFirst() getFirst}.
0N/A *
0N/A * @return the head of the queue represented by this deque
0N/A * @throws NoSuchElementException if this deque is empty
0N/A */
0N/A public E element() {
0N/A return getFirst();
0N/A }
0N/A
0N/A public E peek() {
0N/A return peekFirst();
0N/A }
0N/A
0N/A /**
0N/A * Returns the number of additional elements that this deque can ideally
0N/A * (in the absence of memory or resource constraints) accept without
0N/A * blocking. This is always equal to the initial capacity of this deque
1468N/A * less the current {@code size} of this deque.
0N/A *
0N/A * <p>Note that you <em>cannot</em> always tell if an attempt to insert
1468N/A * an element will succeed by inspecting {@code remainingCapacity}
0N/A * because it may be the case that another thread is about to
0N/A * insert or remove an element.
0N/A */
0N/A public int remainingCapacity() {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return capacity - count;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @throws UnsupportedOperationException {@inheritDoc}
0N/A * @throws ClassCastException {@inheritDoc}
0N/A * @throws NullPointerException {@inheritDoc}
0N/A * @throws IllegalArgumentException {@inheritDoc}
0N/A */
0N/A public int drainTo(Collection<? super E> c) {
1468N/A return drainTo(c, Integer.MAX_VALUE);
0N/A }
0N/A
0N/A /**
0N/A * @throws UnsupportedOperationException {@inheritDoc}
0N/A * @throws ClassCastException {@inheritDoc}
0N/A * @throws NullPointerException {@inheritDoc}
0N/A * @throws IllegalArgumentException {@inheritDoc}
0N/A */
0N/A public int drainTo(Collection<? super E> c, int maxElements) {
0N/A if (c == null)
0N/A throw new NullPointerException();
0N/A if (c == this)
0N/A throw new IllegalArgumentException();
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
1468N/A int n = Math.min(maxElements, count);
1468N/A for (int i = 0; i < n; i++) {
1468N/A c.add(first.item); // In this order, in case add() throws.
1468N/A unlinkFirst();
0N/A }
0N/A return n;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A // Stack methods
0N/A
0N/A /**
0N/A * @throws IllegalStateException {@inheritDoc}
0N/A * @throws NullPointerException {@inheritDoc}
0N/A */
0N/A public void push(E e) {
0N/A addFirst(e);
0N/A }
0N/A
0N/A /**
0N/A * @throws NoSuchElementException {@inheritDoc}
0N/A */
0N/A public E pop() {
0N/A return removeFirst();
0N/A }
0N/A
0N/A // Collection methods
0N/A
0N/A /**
0N/A * Removes the first occurrence of the specified element from this deque.
0N/A * If the deque does not contain the element, it is unchanged.
1468N/A * More formally, removes the first element {@code e} such that
1468N/A * {@code o.equals(e)} (if such an element exists).
1468N/A * Returns {@code true} if this deque contained the specified element
0N/A * (or equivalently, if this deque changed as a result of the call).
0N/A *
0N/A * <p>This method is equivalent to
0N/A * {@link #removeFirstOccurrence(Object) removeFirstOccurrence}.
0N/A *
0N/A * @param o element to be removed from this deque, if present
1468N/A * @return {@code true} if this deque changed as a result of the call
0N/A */
0N/A public boolean remove(Object o) {
0N/A return removeFirstOccurrence(o);
0N/A }
0N/A
0N/A /**
0N/A * Returns the number of elements in this deque.
0N/A *
0N/A * @return the number of elements in this deque
0N/A */
0N/A public int size() {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return count;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
1468N/A * Returns {@code true} if this deque contains the specified element.
1468N/A * More formally, returns {@code true} if and only if this deque contains
1468N/A * at least one element {@code e} such that {@code o.equals(e)}.
0N/A *
0N/A * @param o object to be checked for containment in this deque
1468N/A * @return {@code true} if this deque contains the specified element
0N/A */
0N/A public boolean contains(Object o) {
0N/A if (o == null) return false;
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A for (Node<E> p = first; p != null; p = p.next)
0N/A if (o.equals(p.item))
0N/A return true;
0N/A return false;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
1468N/A /*
1468N/A * TODO: Add support for more efficient bulk operations.
1468N/A *
1468N/A * We don't want to acquire the lock for every iteration, but we
1468N/A * also want other threads a chance to interact with the
1468N/A * collection, especially when count is close to capacity.
0N/A */
1468N/A
1468N/A// /**
1468N/A// * Adds all of the elements in the specified collection to this
1468N/A// * queue. Attempts to addAll of a queue to itself result in
1468N/A// * {@code IllegalArgumentException}. Further, the behavior of
1468N/A// * this operation is undefined if the specified collection is
1468N/A// * modified while the operation is in progress.
1468N/A// *
1468N/A// * @param c collection containing elements to be added to this queue
1468N/A// * @return {@code true} if this queue changed as a result of the call
1468N/A// * @throws ClassCastException {@inheritDoc}
1468N/A// * @throws NullPointerException {@inheritDoc}
1468N/A// * @throws IllegalArgumentException {@inheritDoc}
1468N/A// * @throws IllegalStateException {@inheritDoc}
1468N/A// * @see #add(Object)
1468N/A// */
1468N/A// public boolean addAll(Collection<? extends E> c) {
1468N/A// if (c == null)
1468N/A// throw new NullPointerException();
1468N/A// if (c == this)
1468N/A// throw new IllegalArgumentException();
1468N/A// final ReentrantLock lock = this.lock;
1468N/A// lock.lock();
1468N/A// try {
1468N/A// boolean modified = false;
1468N/A// for (E e : c)
1468N/A// if (linkLast(e))
1468N/A// modified = true;
1468N/A// return modified;
1468N/A// } finally {
1468N/A// lock.unlock();
1468N/A// }
1468N/A// }
0N/A
0N/A /**
0N/A * Returns an array containing all of the elements in this deque, in
0N/A * proper sequence (from first to last element).
0N/A *
0N/A * <p>The returned array will be "safe" in that no references to it are
0N/A * maintained by this deque. (In other words, this method must allocate
0N/A * a new array). The caller is thus free to modify the returned array.
0N/A *
0N/A * <p>This method acts as bridge between array-based and collection-based
0N/A * APIs.
0N/A *
0N/A * @return an array containing all of the elements in this deque
0N/A */
1468N/A @SuppressWarnings("unchecked")
0N/A public Object[] toArray() {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A Object[] a = new Object[count];
0N/A int k = 0;
0N/A for (Node<E> p = first; p != null; p = p.next)
0N/A a[k++] = p.item;
0N/A return a;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an array containing all of the elements in this deque, in
0N/A * proper sequence; the runtime type of the returned array is that of
0N/A * the specified array. If the deque fits in the specified array, it
0N/A * is returned therein. Otherwise, a new array is allocated with the
0N/A * runtime type of the specified array and the size of this deque.
0N/A *
0N/A * <p>If this deque fits in the specified array with room to spare
0N/A * (i.e., the array has more elements than this deque), the element in
0N/A * the array immediately following the end of the deque is set to
1468N/A * {@code null}.
0N/A *
0N/A * <p>Like the {@link #toArray()} method, this method acts as bridge between
0N/A * array-based and collection-based APIs. Further, this method allows
0N/A * precise control over the runtime type of the output array, and may,
0N/A * under certain circumstances, be used to save allocation costs.
0N/A *
1468N/A * <p>Suppose {@code x} is a deque known to contain only strings.
0N/A * The following code can be used to dump the deque into a newly
1468N/A * allocated array of {@code String}:
0N/A *
0N/A * <pre>
0N/A * String[] y = x.toArray(new String[0]);</pre>
0N/A *
1468N/A * Note that {@code toArray(new Object[0])} is identical in function to
1468N/A * {@code toArray()}.
0N/A *
0N/A * @param a the array into which the elements of the deque are to
0N/A * be stored, if it is big enough; otherwise, a new array of the
0N/A * same runtime type is allocated for this purpose
0N/A * @return an array containing all of the elements in this deque
0N/A * @throws ArrayStoreException if the runtime type of the specified array
0N/A * is not a supertype of the runtime type of every element in
0N/A * this deque
0N/A * @throws NullPointerException if the specified array is null
0N/A */
1468N/A @SuppressWarnings("unchecked")
0N/A public <T> T[] toArray(T[] a) {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A if (a.length < count)
1468N/A a = (T[])java.lang.reflect.Array.newInstance
1468N/A (a.getClass().getComponentType(), count);
0N/A
0N/A int k = 0;
0N/A for (Node<E> p = first; p != null; p = p.next)
0N/A a[k++] = (T)p.item;
0N/A if (a.length > k)
0N/A a[k] = null;
0N/A return a;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public String toString() {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
3059N/A Node<E> p = first;
3059N/A if (p == null)
3059N/A return "[]";
3059N/A
3059N/A StringBuilder sb = new StringBuilder();
3059N/A sb.append('[');
3059N/A for (;;) {
3059N/A E e = p.item;
3059N/A sb.append(e == this ? "(this Collection)" : e);
3059N/A p = p.next;
3059N/A if (p == null)
3059N/A return sb.append(']').toString();
3059N/A sb.append(',').append(' ');
3059N/A }
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Atomically removes all of the elements from this deque.
0N/A * The deque will be empty after this call returns.
0N/A */
0N/A public void clear() {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
1468N/A for (Node<E> f = first; f != null; ) {
1468N/A f.item = null;
1468N/A Node<E> n = f.next;
1468N/A f.prev = null;
1468N/A f.next = null;
1468N/A f = n;
1468N/A }
0N/A first = last = null;
0N/A count = 0;
0N/A notFull.signalAll();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an iterator over the elements in this deque in proper sequence.
0N/A * The elements will be returned in order from first (head) to last (tail).
3203N/A *
3203N/A * <p>The returned iterator is a "weakly consistent" iterator that
1472N/A * will never throw {@link java.util.ConcurrentModificationException
3203N/A * ConcurrentModificationException}, and guarantees to traverse
3203N/A * elements as they existed upon construction of the iterator, and
3203N/A * may (but is not guaranteed to) reflect any modifications
3203N/A * subsequent to construction.
0N/A *
0N/A * @return an iterator over the elements in this deque in proper sequence
0N/A */
0N/A public Iterator<E> iterator() {
0N/A return new Itr();
0N/A }
0N/A
0N/A /**
0N/A * Returns an iterator over the elements in this deque in reverse
0N/A * sequential order. The elements will be returned in order from
0N/A * last (tail) to first (head).
3203N/A *
3203N/A * <p>The returned iterator is a "weakly consistent" iterator that
1472N/A * will never throw {@link java.util.ConcurrentModificationException
3203N/A * ConcurrentModificationException}, and guarantees to traverse
3203N/A * elements as they existed upon construction of the iterator, and
3203N/A * may (but is not guaranteed to) reflect any modifications
3203N/A * subsequent to construction.
3387N/A *
3387N/A * @return an iterator over the elements in this deque in reverse order
0N/A */
0N/A public Iterator<E> descendingIterator() {
0N/A return new DescendingItr();
0N/A }
0N/A
0N/A /**
0N/A * Base class for Iterators for LinkedBlockingDeque
0N/A */
0N/A private abstract class AbstractItr implements Iterator<E> {
0N/A /**
1468N/A * The next node to return in next()
0N/A */
0N/A Node<E> next;
0N/A
0N/A /**
0N/A * nextItem holds on to item fields because once we claim that
0N/A * an element exists in hasNext(), we must return item read
0N/A * under lock (in advance()) even if it was in the process of
0N/A * being removed when hasNext() was called.
0N/A */
0N/A E nextItem;
0N/A
0N/A /**
0N/A * Node returned by most recent call to next. Needed by remove.
0N/A * Reset to null if this element is deleted by a call to remove.
0N/A */
0N/A private Node<E> lastRet;
0N/A
1468N/A abstract Node<E> firstNode();
1468N/A abstract Node<E> nextNode(Node<E> n);
1468N/A
0N/A AbstractItr() {
1468N/A // set to initial position
1468N/A final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1468N/A lock.lock();
1468N/A try {
1468N/A next = firstNode();
1468N/A nextItem = (next == null) ? null : next.item;
1468N/A } finally {
1468N/A lock.unlock();
1468N/A }
0N/A }
0N/A
0N/A /**
3059N/A * Returns the successor node of the given non-null, but
3059N/A * possibly previously deleted, node.
3059N/A */
3059N/A private Node<E> succ(Node<E> n) {
3059N/A // Chains of deleted nodes ending in null or self-links
3059N/A // are possible if multiple interior nodes are removed.
3059N/A for (;;) {
3059N/A Node<E> s = nextNode(n);
3059N/A if (s == null)
3059N/A return null;
3059N/A else if (s.item != null)
3059N/A return s;
3059N/A else if (s == n)
3059N/A return firstNode();
3059N/A else
3059N/A n = s;
3059N/A }
3059N/A }
3059N/A
3059N/A /**
1468N/A * Advances next.
0N/A */
1468N/A void advance() {
1468N/A final ReentrantLock lock = LinkedBlockingDeque.this.lock;
1468N/A lock.lock();
1468N/A try {
1468N/A // assert next != null;
3059N/A next = succ(next);
1468N/A nextItem = (next == null) ? null : next.item;
1468N/A } finally {
1468N/A lock.unlock();
1468N/A }
1468N/A }
0N/A
0N/A public boolean hasNext() {
0N/A return next != null;
0N/A }
0N/A
0N/A public E next() {
0N/A if (next == null)
0N/A throw new NoSuchElementException();
0N/A lastRet = next;
0N/A E x = nextItem;
0N/A advance();
0N/A return x;
0N/A }
0N/A
0N/A public void remove() {
0N/A Node<E> n = lastRet;
0N/A if (n == null)
0N/A throw new IllegalStateException();
0N/A lastRet = null;
0N/A final ReentrantLock lock = LinkedBlockingDeque.this.lock;
0N/A lock.lock();
0N/A try {
1468N/A if (n.item != null)
1468N/A unlink(n);
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A }
0N/A
1468N/A /** Forward iterator */
1468N/A private class Itr extends AbstractItr {
1468N/A Node<E> firstNode() { return first; }
1468N/A Node<E> nextNode(Node<E> n) { return n.next; }
1468N/A }
1468N/A
1468N/A /** Descending iterator */
0N/A private class DescendingItr extends AbstractItr {
1468N/A Node<E> firstNode() { return last; }
1468N/A Node<E> nextNode(Node<E> n) { return n.prev; }
0N/A }
0N/A
0N/A /**
0N/A * Save the state of this deque to a stream (that is, serialize it).
0N/A *
0N/A * @serialData The capacity (int), followed by elements (each an
1468N/A * {@code Object}) in the proper order, followed by a null
0N/A * @param s the stream
0N/A */
0N/A private void writeObject(java.io.ObjectOutputStream s)
0N/A throws java.io.IOException {
1468N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A // Write out capacity and any hidden stuff
0N/A s.defaultWriteObject();
0N/A // Write out all elements in the proper order.
0N/A for (Node<E> p = first; p != null; p = p.next)
0N/A s.writeObject(p.item);
0N/A // Use trailing null as sentinel
0N/A s.writeObject(null);
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Reconstitute this deque from a stream (that is,
0N/A * deserialize it).
0N/A * @param s the stream
0N/A */
0N/A private void readObject(java.io.ObjectInputStream s)
0N/A throws java.io.IOException, ClassNotFoundException {
0N/A s.defaultReadObject();
0N/A count = 0;
0N/A first = null;
0N/A last = null;
0N/A // Read in all elements and place in queue
0N/A for (;;) {
1468N/A @SuppressWarnings("unchecked")
0N/A E item = (E)s.readObject();
0N/A if (item == null)
0N/A break;
0N/A add(item);
0N/A }
0N/A }
0N/A
0N/A}