LinkedBlockingDeque.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.pool2.impl;

  18. import java.io.IOException;
  19. import java.io.ObjectInputStream;
  20. import java.io.Serializable;
  21. import java.time.Duration;
  22. import java.util.AbstractQueue;
  23. import java.util.Collection;
  24. import java.util.Deque;
  25. import java.util.Iterator;
  26. import java.util.NoSuchElementException;
  27. import java.util.Objects;
  28. import java.util.concurrent.TimeUnit;
  29. import java.util.concurrent.locks.Condition;

  30. /**
  31.  * An optionally-bounded {@linkplain java.util.concurrent.BlockingDeque blocking
  32.  * deque} based on linked nodes.
  33.  *
  34.  * <p> The optional capacity bound constructor argument serves as a
  35.  * way to prevent excessive expansion. The capacity, if unspecified,
  36.  * is equal to {@link Integer#MAX_VALUE}.  Linked nodes are
  37.  * dynamically created upon each insertion unless this would bring the
  38.  * deque above capacity.
  39.  * </p>
  40.  *
  41.  * <p>Most operations run in constant time (ignoring time spent
  42.  * blocking).  Exceptions include {@link #remove(Object) remove},
  43.  * {@link #removeFirstOccurrence removeFirstOccurrence}, {@link
  44.  * #removeLastOccurrence removeLastOccurrence}, {@link #contains
  45.  * contains}, {@link #iterator iterator.remove()}, and the bulk
  46.  * operations, all of which run in linear time.
  47.  * </p>
  48.  *
  49.  * <p>This class and its iterator implement all of the
  50.  * <em>optional</em> methods of the {@link Collection} and {@link
  51.  * Iterator} interfaces.
  52.  * </p>
  53.  *
  54.  * <p>This class is a member of the
  55.  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
  56.  * Java Collections Framework</a>.
  57.  * </p>
  58.  *
  59.  * @param <E> the type of elements held in this collection
  60.  *
  61.  * Note: This was copied from Apache Harmony and modified to suit the needs of
  62.  *       Commons Pool.
  63.  *
  64.  * @since 2.0
  65.  */
  66. final class LinkedBlockingDeque<E> extends AbstractQueue<E>
  67.         implements Deque<E>, Serializable {

  68.     /*
  69.      * Implemented as a simple doubly-linked list protected by a
  70.      * single lock and using conditions to manage blocking.
  71.      *
  72.      * To implement weakly consistent iterators, it appears we need to
  73.      * keep all Nodes GC-reachable from a predecessor dequeued Node.
  74.      * That would cause two problems:
  75.      * - allow a rogue Iterator to cause unbounded memory retention
  76.      * - cause cross-generational linking of old Nodes to new Nodes if
  77.      *   a Node was tenured while live, which generational GCs have a
  78.      *   hard time dealing with, causing repeated major collections.
  79.      * However, only non-deleted Nodes need to be reachable from
  80.      * dequeued Nodes, and reachability does not necessarily have to
  81.      * be of the kind understood by the GC.  We use the trick of
  82.      * linking a Node that has just been dequeued to itself.  Such a
  83.      * self-link implicitly means to jump to "first" (for next links)
  84.      * or "last" (for prev links).
  85.      */

  86.     /*
  87.      * We have "diamond" multiple interface/abstract class inheritance
  88.      * here, and that introduces ambiguities. Often we want the
  89.      * BlockingDeque javadoc combined with the AbstractQueue
  90.      * implementation, so a lot of method specs are duplicated here.
  91.      */

  92.     /**
  93.      * Base class for Iterators for LinkedBlockingDeque
  94.      */
  95.     private abstract class AbstractItr implements Iterator<E> {
  96.         /**
  97.          * The next node to return in next()
  98.          */
  99.          Node<E> next;

  100.         /**
  101.          * nextItem holds on to item fields because once we claim that
  102.          * an element exists in hasNext(), we must return item read
  103.          * under lock (in advance()) even if it was in the process of
  104.          * being removed when hasNext() was called.
  105.          */
  106.         E nextItem;

  107.         /**
  108.          * Node returned by most recent call to next. Needed by remove.
  109.          * Reset to null if this element is deleted by a call to remove.
  110.          */
  111.         private Node<E> lastRet;

  112.         /**
  113.          * Constructs a new iterator. Sets the initial position.
  114.          */
  115.         AbstractItr() {
  116.             // set to initial position
  117.             lock.lock();
  118.             try {
  119.                 next = firstNode();
  120.                 nextItem = next == null ? null : next.item;
  121.             } finally {
  122.                 lock.unlock();
  123.             }
  124.         }

  125.         /**
  126.          * Advances next.
  127.          */
  128.         void advance() {
  129.             lock.lock();
  130.             try {
  131.                 // assert next != null;
  132.                 next = succ(next);
  133.                 nextItem = next == null ? null : next.item;
  134.             } finally {
  135.                 lock.unlock();
  136.             }
  137.         }

  138.         /**
  139.          * Obtain the first node to be returned by the iterator.
  140.          *
  141.          * @return first node
  142.          */
  143.         abstract Node<E> firstNode();

  144.         @Override
  145.         public boolean hasNext() {
  146.             return next != null;
  147.         }

  148.         @Override
  149.         public E next() {
  150.             if (next == null) {
  151.                 throw new NoSuchElementException();
  152.             }
  153.             lastRet = next;
  154.             final E x = nextItem;
  155.             advance();
  156.             return x;
  157.         }

  158.         /**
  159.          * For a given node, obtain the next node to be returned by the
  160.          * iterator.
  161.          *
  162.          * @param n given node
  163.          * @return next node
  164.          */
  165.         abstract Node<E> nextNode(Node<E> n);

  166.         @Override
  167.         public void remove() {
  168.             final Node<E> n = lastRet;
  169.             if (n == null) {
  170.                 throw new IllegalStateException();
  171.             }
  172.             lastRet = null;
  173.             lock.lock();
  174.             try {
  175.                 if (n.item != null) {
  176.                     unlink(n);
  177.                 }
  178.             } finally {
  179.                 lock.unlock();
  180.             }
  181.         }

  182.         /**
  183.          * Returns the successor node of the given non-null, but
  184.          * possibly previously deleted, node.
  185.          *
  186.          * @param n node whose successor is sought
  187.          * @return successor node
  188.          */
  189.         private Node<E> succ(Node<E> n) {
  190.             // Chains of deleted nodes ending in null or self-links
  191.             // are possible if multiple interior nodes are removed.
  192.             for (;;) {
  193.                 final Node<E> s = nextNode(n);
  194.                 if (s == null) {
  195.                     return null;
  196.                 }
  197.                 if (s.item != null) {
  198.                     return s;
  199.                 }
  200.                 if (s == n) {
  201.                     return firstNode();
  202.                 }
  203.                 n = s;
  204.             }
  205.         }
  206.     }

  207.     /** Descending iterator */
  208.     private final class DescendingItr extends AbstractItr {
  209.         @Override
  210.         Node<E> firstNode() { return last; }
  211.         @Override
  212.         Node<E> nextNode(final Node<E> n) { return n.prev; }
  213.     }

  214.     /** Forward iterator */
  215.     private final class Itr extends AbstractItr {
  216.         @Override
  217.         Node<E> firstNode() { return first; }
  218.         @Override
  219.         Node<E> nextNode(final Node<E> n) { return n.next; }
  220.         }

  221.     /**
  222.      * Doubly-linked list node class.
  223.      *
  224.      * @param <E> node item type
  225.      */
  226.     private static final class Node<E> {
  227.         /**
  228.          * The item, or null if this node has been removed.
  229.          */
  230.         E item;

  231.         /**
  232.          * One of:
  233.          * - the real predecessor Node
  234.          * - this Node, meaning the predecessor is tail
  235.          * - null, meaning there is no predecessor
  236.          */
  237.         Node<E> prev;

  238.         /**
  239.          * One of:
  240.          * - the real successor Node
  241.          * - this Node, meaning the successor is head
  242.          * - null, meaning there is no successor
  243.          */
  244.         Node<E> next;

  245.         /**
  246.          * Constructs a new list node.
  247.          *
  248.          * @param x The list item
  249.          * @param p Previous item
  250.          * @param n Next item
  251.          */
  252.         Node(final E x, final Node<E> p, final Node<E> n) {
  253.             item = x;
  254.             prev = p;
  255.             next = n;
  256.         }
  257.     }

  258.     private static final long serialVersionUID = -387911632671998426L;

  259.     /**
  260.      * Pointer to first node.
  261.      * Invariant: (first == null && last == null) ||
  262.      *            (first.prev == null && first.item != null)
  263.      */
  264.     private transient Node<E> first; // @GuardedBy("lock")

  265.     /**
  266.      * Pointer to last node.
  267.      * Invariant: (first == null && last == null) ||
  268.      *            (last.next == null && last.item != null)
  269.      */
  270.     private transient Node<E> last; // @GuardedBy("lock")

  271.     /** Number of items in the deque */
  272.     private transient int count; // @GuardedBy("lock")

  273.     /** Maximum number of items in the deque */
  274.     private final int capacity;

  275.     /** Main lock guarding all access */
  276.     private final InterruptibleReentrantLock lock;

  277.     /** Condition for waiting takes */
  278.     private final Condition notEmpty;

  279.     /** Condition for waiting puts */
  280.     private final Condition notFull;

  281.     /**
  282.      * Creates a {@code LinkedBlockingDeque} with a capacity of
  283.      * {@link Integer#MAX_VALUE}.
  284.      */
  285.     public LinkedBlockingDeque() {
  286.         this(Integer.MAX_VALUE);
  287.     }

  288.     /**
  289.      * Creates a {@code LinkedBlockingDeque} with a capacity of
  290.      * {@link Integer#MAX_VALUE} and the given fairness policy.
  291.      * @param fairness true means threads waiting on the deque should be served
  292.      * as if waiting in a FIFO request queue
  293.      */
  294.     public LinkedBlockingDeque(final boolean fairness) {
  295.         this(Integer.MAX_VALUE, fairness);
  296.     }

  297.     // Basic linking and unlinking operations, called only while holding lock

  298.     /**
  299.      * Creates a {@code LinkedBlockingDeque} with a capacity of
  300.      * {@link Integer#MAX_VALUE}, initially containing the elements of
  301.      * the given collection, added in traversal order of the
  302.      * collection's iterator.
  303.      *
  304.      * @param c the collection of elements to initially contain
  305.      * @throws NullPointerException if the specified collection or any
  306.      *         of its elements are null
  307.      */
  308.     public LinkedBlockingDeque(final Collection<? extends E> c) {
  309.         this(Integer.MAX_VALUE);
  310.         lock.lock(); // Never contended, but necessary for visibility
  311.         try {
  312.             for (final E e : c) {
  313.                 Objects.requireNonNull(e);
  314.                 if (!linkLast(e)) {
  315.                     throw new IllegalStateException("Deque full");
  316.                 }
  317.             }
  318.         } finally {
  319.             lock.unlock();
  320.         }
  321.     }

  322.     /**
  323.      * Creates a {@code LinkedBlockingDeque} with the given (fixed) capacity.
  324.      *
  325.      * @param capacity the capacity of this deque
  326.      * @throws IllegalArgumentException if {@code capacity} is less than 1
  327.      */
  328.     public LinkedBlockingDeque(final int capacity) {
  329.         this(capacity, false);
  330.     }

  331.     /**
  332.      * Creates a {@code LinkedBlockingDeque} with the given (fixed) capacity
  333.      * and fairness policy.
  334.      *
  335.      * @param capacity the capacity of this deque
  336.      * @param fairness true means threads waiting on the deque should be served
  337.      * as if waiting in a FIFO request queue
  338.      * @throws IllegalArgumentException if {@code capacity} is less than 1
  339.      */
  340.     public LinkedBlockingDeque(final int capacity, final boolean fairness) {
  341.         if (capacity <= 0) {
  342.             throw new IllegalArgumentException();
  343.         }
  344.         this.capacity = capacity;
  345.         lock = new InterruptibleReentrantLock(fairness);
  346.         notEmpty = lock.newCondition();
  347.         notFull = lock.newCondition();
  348.     }

  349.     /**
  350.      * {@inheritDoc}
  351.      */
  352.     @Override
  353.     public boolean add(final E e) {
  354.         addLast(e);
  355.         return true;
  356.     }

  357.     /**
  358.      * {@inheritDoc}
  359.      */
  360.     @Override
  361.     public void addFirst(final E e) {
  362.         if (!offerFirst(e)) {
  363.             throw new IllegalStateException("Deque full");
  364.         }
  365.     }

  366.     // BlockingDeque methods

  367.     /**
  368.      * {@inheritDoc}
  369.      */
  370.     @Override
  371.     public void addLast(final E e) {
  372.         if (!offerLast(e)) {
  373.             throw new IllegalStateException("Deque full");
  374.         }
  375.     }

  376.     /**
  377.      * Atomically removes all of the elements from this deque.
  378.      * The deque will be empty after this call returns.
  379.      */
  380.     @Override
  381.     public void clear() {
  382.         lock.lock();
  383.         try {
  384.             for (Node<E> f = first; f != null;) {
  385.                 f.item = null;
  386.                 final Node<E> n = f.next;
  387.                 f.prev = null;
  388.                 f.next = null;
  389.                 f = n;
  390.             }
  391.             first = last = null;
  392.             count = 0;
  393.             notFull.signalAll();
  394.         } finally {
  395.             lock.unlock();
  396.         }
  397.     }

  398.     /**
  399.      * Returns {@code true} if this deque contains the specified element.
  400.      * More formally, returns {@code true} if and only if this deque contains
  401.      * at least one element {@code e} such that {@code o.equals(e)}.
  402.      *
  403.      * @param o object to be checked for containment in this deque
  404.      * @return {@code true} if this deque contains the specified element
  405.      */
  406.     @Override
  407.     public boolean contains(final Object o) {
  408.         if (o == null) {
  409.             return false;
  410.         }
  411.         lock.lock();
  412.         try {
  413.             for (Node<E> p = first; p != null; p = p.next) {
  414.                 if (o.equals(p.item)) {
  415.                     return true;
  416.                 }
  417.             }
  418.             return false;
  419.         } finally {
  420.             lock.unlock();
  421.         }
  422.     }

  423.     /**
  424.      * {@inheritDoc}
  425.      */
  426.     @Override
  427.     public Iterator<E> descendingIterator() {
  428.         return new DescendingItr();
  429.     }

  430.     /**
  431.      * Drains the queue to the specified collection.
  432.      *
  433.      * @param c The collection to add the elements to
  434.      * @return number of elements added to the collection
  435.      * @throws UnsupportedOperationException if the add operation is not
  436.      *         supported by the specified collection
  437.      * @throws ClassCastException if the class of the elements held by this
  438.      *         collection prevents them from being added to the specified
  439.      *         collection
  440.      * @throws NullPointerException if c is null
  441.      * @throws IllegalArgumentException if c is this instance
  442.      */
  443.     public int drainTo(final Collection<? super E> c) {
  444.         return drainTo(c, Integer.MAX_VALUE);
  445.     }

  446.     /**
  447.      * Drains no more than the specified number of elements from the queue to the
  448.      * specified collection.
  449.      *
  450.      * @param collection collection to add the elements to
  451.      * @param maxElements maximum number of elements to remove from the queue
  452.      * @return number of elements added to the collection
  453.      * @throws UnsupportedOperationException if the add operation is not
  454.      *         supported by the specified collection
  455.      * @throws ClassCastException if the class of the elements held by this
  456.      *         collection prevents them from being added to the specified
  457.      *         collection
  458.      * @throws NullPointerException if c is null
  459.      * @throws IllegalArgumentException if c is this instance
  460.      */
  461.     public int drainTo(final Collection<? super E> collection, final int maxElements) {
  462.         Objects.requireNonNull(collection, "collection");
  463.         if (collection == this) {
  464.             throw new IllegalArgumentException();
  465.         }
  466.         lock.lock();
  467.         try {
  468.             final int n = Math.min(maxElements, count);
  469.             for (int i = 0; i < n; i++) {
  470.                 collection.add(first.item); // In this order, in case add() throws.
  471.                 unlinkFirst();
  472.             }
  473.             return n;
  474.         } finally {
  475.             lock.unlock();
  476.         }
  477.     }

  478.     /**
  479.      * Retrieves, but does not remove, the head of the queue represented by
  480.      * this deque.  This method differs from {@link #peek peek} only in that
  481.      * it throws an exception if this deque is empty.
  482.      *
  483.      * <p>This method is equivalent to {@link #getFirst() getFirst}.
  484.      *
  485.      * @return the head of the queue represented by this deque
  486.      * @throws NoSuchElementException if this deque is empty
  487.      */
  488.     @Override
  489.     public E element() {
  490.         return getFirst();
  491.     }

  492.     /**
  493.      * {@inheritDoc}
  494.      */
  495.     @Override
  496.     public E getFirst() {
  497.         final E x = peekFirst();
  498.         if (x == null) {
  499.             throw new NoSuchElementException();
  500.         }
  501.         return x;
  502.     }

  503.     /**
  504.      * {@inheritDoc}
  505.      */
  506.     @Override
  507.     public E getLast() {
  508.         final E x = peekLast();
  509.         if (x == null) {
  510.             throw new NoSuchElementException();
  511.         }
  512.         return x;
  513.     }

  514.     /**
  515.      * Gets the length of the queue of threads waiting to take instances from this deque. See disclaimer on accuracy
  516.      * in {@link java.util.concurrent.locks.ReentrantLock#getWaitQueueLength(Condition)}.
  517.      *
  518.      * @return number of threads waiting on this deque's notEmpty condition.
  519.      */
  520.     public int getTakeQueueLength() {
  521.         lock.lock();
  522.         try {
  523.            return lock.getWaitQueueLength(notEmpty);
  524.         } finally {
  525.             lock.unlock();
  526.         }
  527.     }

  528.     /**
  529.      * Returns true if there are threads waiting to take instances from this deque. See disclaimer on accuracy in
  530.      * {@link java.util.concurrent.locks.ReentrantLock#hasWaiters(Condition)}.
  531.      *
  532.      * @return true if there is at least one thread waiting on this deque's notEmpty condition.
  533.      */
  534.     public boolean hasTakeWaiters() {
  535.         lock.lock();
  536.         try {
  537.             return lock.hasWaiters(notEmpty);
  538.         } finally {
  539.             lock.unlock();
  540.         }
  541.     }

  542.     /**
  543.      * Interrupts the threads currently waiting to take an object from the pool. See disclaimer on accuracy in
  544.      * {@link java.util.concurrent.locks.ReentrantLock#getWaitingThreads(Condition)}.
  545.      */
  546.     public void interuptTakeWaiters() {
  547.         lock.lock();
  548.         try {
  549.             lock.interruptWaiters(notEmpty);
  550.         } finally {
  551.             lock.unlock();
  552.         }
  553.     }

  554.     /**
  555.      * Returns an iterator over the elements in this deque in proper sequence.
  556.      * The elements will be returned in order from first (head) to last (tail).
  557.      * The returned {@code Iterator} is a "weakly consistent" iterator that
  558.      * will never throw {@link java.util.ConcurrentModificationException
  559.      * ConcurrentModificationException},
  560.      * and guarantees to traverse elements as they existed upon
  561.      * construction of the iterator, and may (but is not guaranteed to)
  562.      * reflect any modifications subsequent to construction.
  563.      *
  564.      * @return an iterator over the elements in this deque in proper sequence
  565.      */
  566.     @Override
  567.     public Iterator<E> iterator() {
  568.         return new Itr();
  569.     }

  570.     /**
  571.      * Links provided element as first element, or returns false if full.
  572.      *
  573.      * @param e The element to link as the first element.
  574.      * @return {@code true} if successful, otherwise {@code false}
  575.      */
  576.     private boolean linkFirst(final E e) {
  577.         // assert lock.isHeldByCurrentThread();
  578.         if (count >= capacity) {
  579.             return false;
  580.         }
  581.         final Node<E> f = first;
  582.         final Node<E> x = new Node<>(e, null, f);
  583.         first = x;
  584.         if (last == null) {
  585.             last = x;
  586.         } else {
  587.             f.prev = x;
  588.         }
  589.         ++count;
  590.         notEmpty.signal();
  591.         return true;
  592.     }

  593.     /**
  594.      * Links provided element as last element, or returns false if full.
  595.      *
  596.      * @param e The element to link as the last element.
  597.      * @return {@code true} if successful, otherwise {@code false}
  598.      */
  599.     private boolean linkLast(final E e) {
  600.         // assert lock.isHeldByCurrentThread();
  601.         if (count >= capacity) {
  602.             return false;
  603.         }
  604.         final Node<E> l = last;
  605.         final Node<E> x = new Node<>(e, l, null);
  606.         last = x;
  607.         if (first == null) {
  608.             first = x;
  609.         } else {
  610.             l.next = x;
  611.         }
  612.         ++count;
  613.         notEmpty.signal();
  614.         return true;
  615.     }

  616.     /**
  617.      * {@inheritDoc}
  618.      */
  619.     @Override
  620.     public boolean offer(final E e) {
  621.         return offerLast(e);
  622.     }

  623.     /**
  624.      * Links the provided element as the last in the queue, waiting up to the
  625.      * specified time to do so if the queue is full.
  626.      * <p>
  627.      * This method is equivalent to {@link #offerLast(Object, long, TimeUnit)}
  628.      *
  629.      * @param e         element to link
  630.      * @param timeout   length of time to wait
  631.      * @return {@code true} if successful, otherwise {@code false}
  632.      * @throws NullPointerException if e is null
  633.      * @throws InterruptedException if the thread is interrupted whilst waiting
  634.      *         for space
  635.      */
  636.     boolean offer(final E e, final Duration timeout) throws InterruptedException {
  637.         return offerLast(e, timeout);
  638.     }

  639.     /**
  640.      * Links the provided element as the last in the queue, waiting up to the
  641.      * specified time to do so if the queue is full.
  642.      * <p>
  643.      * This method is equivalent to {@link #offerLast(Object, long, TimeUnit)}
  644.      *
  645.      * @param e         element to link
  646.      * @param timeout   length of time to wait
  647.      * @param unit      units that timeout is expressed in
  648.      * @return {@code true} if successful, otherwise {@code false}
  649.      * @throws NullPointerException if e is null
  650.      * @throws InterruptedException if the thread is interrupted whilst waiting
  651.      *         for space
  652.      */
  653.     public boolean offer(final E e, final long timeout, final TimeUnit unit) throws InterruptedException {
  654.         return offerLast(e, timeout, unit);
  655.     }

  656.     /**
  657.      * {@inheritDoc}
  658.      */
  659.     @Override
  660.     public boolean offerFirst(final E e) {
  661.         Objects.requireNonNull(e, "e");
  662.         lock.lock();
  663.         try {
  664.             return linkFirst(e);
  665.         } finally {
  666.             lock.unlock();
  667.         }
  668.     }

  669.     /**
  670.      * Links the provided element as the first in the queue, waiting up to the
  671.      * specified time to do so if the queue is full.
  672.      *
  673.      * @param e         element to link
  674.      * @param timeout   length of time to wait
  675.      * @return {@code true} if successful, otherwise {@code false}
  676.      * @throws NullPointerException if e is null
  677.      * @throws InterruptedException if the thread is interrupted whilst waiting
  678.      *         for space
  679.      */
  680.     public boolean offerFirst(final E e, final Duration timeout) throws InterruptedException {
  681.         Objects.requireNonNull(e, "e");
  682.         long nanos = timeout.toNanos();
  683.         lock.lockInterruptibly();
  684.         try {
  685.             while (!linkFirst(e)) {
  686.                 if (nanos <= 0) {
  687.                     return false;
  688.                 }
  689.                 nanos = notFull.awaitNanos(nanos);
  690.             }
  691.             return true;
  692.         } finally {
  693.             lock.unlock();
  694.         }
  695.     }

  696.     /**
  697.      * Links the provided element as the first in the queue, waiting up to the
  698.      * specified time to do so if the queue is full.
  699.      *
  700.      * @param e         element to link
  701.      * @param timeout   length of time to wait
  702.      * @param unit      units that timeout is expressed in
  703.      * @return {@code true} if successful, otherwise {@code false}
  704.      * @throws NullPointerException if e is null
  705.      * @throws InterruptedException if the thread is interrupted whilst waiting
  706.      *         for space
  707.      */
  708.     public boolean offerFirst(final E e, final long timeout, final TimeUnit unit) throws InterruptedException {
  709.         return offerFirst(e, PoolImplUtils.toDuration(timeout, unit));
  710.     }

  711.     /**
  712.      * {@inheritDoc}
  713.      */
  714.     @Override
  715.     public boolean offerLast(final E e) {
  716.         Objects.requireNonNull(e, "e");
  717.         lock.lock();
  718.         try {
  719.             return linkLast(e);
  720.         } finally {
  721.             lock.unlock();
  722.         }
  723.     }

  724.     /**
  725.      * Links the provided element as the last in the queue, waiting up to the
  726.      * specified time to do so if the queue is full.
  727.      *
  728.      * @param e         element to link
  729.      * @param timeout   length of time to wait
  730.      * @return {@code true} if successful, otherwise {@code false}
  731.      * @throws NullPointerException if e is null
  732.      * @throws InterruptedException if the thread is interrupted whist waiting
  733.      *         for space
  734.      */
  735.     boolean offerLast(final E e, final Duration timeout) throws InterruptedException {
  736.         Objects.requireNonNull(e, "e");
  737.         long nanos = timeout.toNanos();
  738.         lock.lockInterruptibly();
  739.         try {
  740.             while (!linkLast(e)) {
  741.                 if (nanos <= 0) {
  742.                     return false;
  743.                 }
  744.                 nanos = notFull.awaitNanos(nanos);
  745.             }
  746.             return true;
  747.         } finally {
  748.             lock.unlock();
  749.         }
  750.     }

  751.     /**
  752.      * Links the provided element as the last in the queue, waiting up to the
  753.      * specified time to do so if the queue is full.
  754.      *
  755.      * @param e         element to link
  756.      * @param timeout   length of time to wait
  757.      * @param unit      units that timeout is expressed in
  758.      * @return {@code true} if successful, otherwise {@code false}
  759.      * @throws NullPointerException if e is null
  760.      * @throws InterruptedException if the thread is interrupted whist waiting
  761.      *         for space
  762.      */
  763.     public boolean offerLast(final E e, final long timeout, final TimeUnit unit) throws InterruptedException {
  764.         return offerLast(e, PoolImplUtils.toDuration(timeout, unit));
  765.     }

  766.     @Override
  767.     public E peek() {
  768.         return peekFirst();
  769.     }

  770.     // BlockingQueue methods

  771.     @Override
  772.     public E peekFirst() {
  773.         lock.lock();
  774.         try {
  775.             return first == null ? null : first.item;
  776.         } finally {
  777.             lock.unlock();
  778.         }
  779.     }

  780.     @Override
  781.     public E peekLast() {
  782.         lock.lock();
  783.         try {
  784.             return last == null ? null : last.item;
  785.         } finally {
  786.             lock.unlock();
  787.         }
  788.     }

  789.     @Override
  790.     public E poll() {
  791.         return pollFirst();
  792.     }

  793.     /**
  794.      * Unlinks the first element in the queue, waiting up to the specified time
  795.      * to do so if the queue is empty.
  796.      *
  797.      * <p>This method is equivalent to {@link #pollFirst(long, TimeUnit)}.
  798.      *
  799.      * @param timeout   length of time to wait
  800.      * @return the unlinked element
  801.      * @throws InterruptedException if the current thread is interrupted
  802.      */
  803.     E poll(final Duration timeout) throws InterruptedException {
  804.         return pollFirst(timeout);
  805.     }

  806.     /**
  807.      * Unlinks the first element in the queue, waiting up to the specified time
  808.      * to do so if the queue is empty.
  809.      *
  810.      * <p>This method is equivalent to {@link #pollFirst(long, TimeUnit)}.
  811.      *
  812.      * @param timeout   length of time to wait
  813.      * @param unit      units that timeout is expressed in
  814.      * @return the unlinked element
  815.      * @throws InterruptedException if the current thread is interrupted
  816.      */
  817.     public E poll(final long timeout, final TimeUnit unit) throws InterruptedException {
  818.         return pollFirst(timeout, unit);
  819.     }

  820.     @Override
  821.     public E pollFirst() {
  822.         lock.lock();
  823.         try {
  824.             return unlinkFirst();
  825.         } finally {
  826.             lock.unlock();
  827.         }
  828.     }

  829.     /**
  830.      * Unlinks the first element in the queue, waiting up to the specified time
  831.      * to do so if the queue is empty.
  832.      *
  833.      * @param timeout   length of time to wait
  834.      * @return the unlinked element
  835.      * @throws InterruptedException if the current thread is interrupted
  836.      */
  837.     E pollFirst(final Duration timeout) throws InterruptedException {
  838.         long nanos = timeout.toNanos();
  839.         lock.lockInterruptibly();
  840.         try {
  841.             E x;
  842.             while ((x = unlinkFirst()) == null) {
  843.                 if (nanos <= 0) {
  844.                     return null;
  845.                 }
  846.                 nanos = notEmpty.awaitNanos(nanos);
  847.             }
  848.             return x;
  849.         } finally {
  850.             lock.unlock();
  851.         }
  852.     }

  853.     /**
  854.      * Unlinks the first element in the queue, waiting up to the specified time
  855.      * to do so if the queue is empty.
  856.      *
  857.      * @param timeout   length of time to wait
  858.      * @param unit      units that timeout is expressed in
  859.      * @return the unlinked element
  860.      * @throws InterruptedException if the current thread is interrupted
  861.      */
  862.     public E pollFirst(final long timeout, final TimeUnit unit) throws InterruptedException {
  863.         return pollFirst(PoolImplUtils.toDuration(timeout, unit));
  864.     }

  865.     @Override
  866.     public E pollLast() {
  867.         lock.lock();
  868.         try {
  869.             return unlinkLast();
  870.         } finally {
  871.             lock.unlock();
  872.         }
  873.     }

  874.     /**
  875.      * Unlinks the last element in the queue, waiting up to the specified time
  876.      * to do so if the queue is empty.
  877.      *
  878.      * @param timeout   length of time to wait
  879.      * @return the unlinked element
  880.      * @throws InterruptedException if the current thread is interrupted
  881.      */
  882.     public E pollLast(final Duration timeout)
  883.         throws InterruptedException {
  884.         long nanos = timeout.toNanos();
  885.         lock.lockInterruptibly();
  886.         try {
  887.             E x;
  888.             while ((x = unlinkLast()) == null) {
  889.                 if (nanos <= 0) {
  890.                     return null;
  891.                 }
  892.                 nanos = notEmpty.awaitNanos(nanos);
  893.             }
  894.             return x;
  895.         } finally {
  896.             lock.unlock();
  897.         }
  898.     }

  899.     /**
  900.      * Unlinks the last element in the queue, waiting up to the specified time
  901.      * to do so if the queue is empty.
  902.      *
  903.      * @param timeout   length of time to wait
  904.      * @param unit      units that timeout is expressed in
  905.      * @return the unlinked element
  906.      * @throws InterruptedException if the current thread is interrupted
  907.      */
  908.     public E pollLast(final long timeout, final TimeUnit unit)
  909.         throws InterruptedException {
  910.         return pollLast(PoolImplUtils.toDuration(timeout, unit));
  911.     }

  912.     /**
  913.      * {@inheritDoc}
  914.      */
  915.     @Override
  916.     public E pop() {
  917.         return removeFirst();
  918.     }

  919.     /**
  920.      * {@inheritDoc}
  921.      */
  922.     @Override
  923.     public void push(final E e) {
  924.         addFirst(e);
  925.     }

  926.     /**
  927.      * Links the provided element as the last in the queue, waiting until there
  928.      * is space to do so if the queue is full.
  929.      *
  930.      * <p>
  931.      * This method is equivalent to {@link #putLast(Object)}.
  932.      * </p>
  933.      *
  934.      * @param e element to link
  935.      * @throws NullPointerException if e is null
  936.      * @throws InterruptedException if the thread is interrupted whilst waiting
  937.      *         for space
  938.      */
  939.     public void put(final E e) throws InterruptedException {
  940.         putLast(e);
  941.     }

  942.     /**
  943.      * Links the provided element as the first in the queue, waiting until there
  944.      * is space to do so if the queue is full.
  945.      *
  946.      * @param e element to link
  947.      * @throws NullPointerException if e is null
  948.      * @throws InterruptedException if the thread is interrupted whilst waiting
  949.      *         for space
  950.      */
  951.     public void putFirst(final E e) throws InterruptedException {
  952.         Objects.requireNonNull(e, "e");
  953.         lock.lock();
  954.         try {
  955.             while (!linkFirst(e)) {
  956.                 notFull.await();
  957.             }
  958.         } finally {
  959.             lock.unlock();
  960.         }
  961.     }

  962.     /**
  963.      * Links the provided element as the last in the queue, waiting until there
  964.      * is space to do so if the queue is full.
  965.      *
  966.      * @param e element to link
  967.      * @throws NullPointerException if e is null
  968.      * @throws InterruptedException if the thread is interrupted whilst waiting
  969.      *         for space
  970.      */
  971.     public void putLast(final E e) throws InterruptedException {
  972.         Objects.requireNonNull(e, "e");
  973.         lock.lock();
  974.         try {
  975.             while (!linkLast(e)) {
  976.                 notFull.await();
  977.             }
  978.         } finally {
  979.             lock.unlock();
  980.         }
  981.     }

  982.     // Stack methods

  983.     /**
  984.      * Reconstitutes this deque from a stream (that is,
  985.      * deserialize it).
  986.      * @param s the stream
  987.      */
  988.     private void readObject(final ObjectInputStream s)
  989.         throws IOException, ClassNotFoundException {
  990.         s.defaultReadObject();
  991.         count = 0;
  992.         first = null;
  993.         last = null;
  994.         // Read in all elements and place in queue
  995.         for (;;) {
  996.             @SuppressWarnings("unchecked")
  997.             final E item = (E)s.readObject();
  998.             if (item == null) {
  999.                 break;
  1000.             }
  1001.             add(item);
  1002.         }
  1003.     }

  1004.     /**
  1005.      * Returns the number of additional elements that this deque can ideally
  1006.      * (in the absence of memory or resource constraints) accept without
  1007.      * blocking. This is always equal to the initial capacity of this deque
  1008.      * less the current {@code size} of this deque.
  1009.      *
  1010.      * <p>
  1011.      * Note that you <em>cannot</em> always tell if an attempt to insert
  1012.      * an element will succeed by inspecting {@code remainingCapacity}
  1013.      * because it may be the case that another thread is about to
  1014.      * insert or remove an element.
  1015.      * </p>
  1016.      *
  1017.      * @return The number of additional elements the queue is able to accept
  1018.      */
  1019.     public int remainingCapacity() {
  1020.         lock.lock();
  1021.         try {
  1022.             return capacity - count;
  1023.         } finally {
  1024.             lock.unlock();
  1025.         }
  1026.     }

  1027.     // Collection methods

  1028.     /**
  1029.      * Retrieves and removes the head of the queue represented by this deque.
  1030.      * This method differs from {@link #poll poll} only in that it throws an
  1031.      * exception if this deque is empty.
  1032.      *
  1033.      * <p>
  1034.      * This method is equivalent to {@link #removeFirst() removeFirst}.
  1035.      * </p>
  1036.      *
  1037.      * @return the head of the queue represented by this deque
  1038.      * @throws NoSuchElementException if this deque is empty
  1039.      */
  1040.     @Override
  1041.     public E remove() {
  1042.         return removeFirst();
  1043.     }

  1044.     /**
  1045.      * Removes the first occurrence of the specified element from this deque.
  1046.      * If the deque does not contain the element, it is unchanged.
  1047.      * More formally, removes the first element {@code e} such that
  1048.      * {@code o.equals(e)} (if such an element exists).
  1049.      * Returns {@code true} if this deque contained the specified element
  1050.      * (or equivalently, if this deque changed as a result of the call).
  1051.      *
  1052.      * <p>
  1053.      * This method is equivalent to
  1054.      * {@link #removeFirstOccurrence(Object) removeFirstOccurrence}.
  1055.      * </p>
  1056.      *
  1057.      * @param o element to be removed from this deque, if present
  1058.      * @return {@code true} if this deque changed as a result of the call
  1059.      */
  1060.     @Override
  1061.     public boolean remove(final Object o) {
  1062.         return removeFirstOccurrence(o);
  1063.     }

  1064.     /**
  1065.      * {@inheritDoc}
  1066.      */
  1067.     @Override
  1068.     public E removeFirst() {
  1069.         final E x = pollFirst();
  1070.         if (x == null) {
  1071.             throw new NoSuchElementException();
  1072.         }
  1073.         return x;
  1074.     }

  1075.     /*
  1076.      * TODO: Add support for more efficient bulk operations.
  1077.      *
  1078.      * We don't want to acquire the lock for every iteration, but we
  1079.      * also want other threads a chance to interact with the
  1080.      * collection, especially when count is close to capacity.
  1081.      */

  1082. //     /**
  1083. //      * Adds all of the elements in the specified collection to this
  1084. //      * queue.  Attempts to addAll of a queue to itself result in
  1085. //      * {@code IllegalArgumentException}. Further, the behavior of
  1086. //      * this operation is undefined if the specified collection is
  1087. //      * modified while the operation is in progress.
  1088. //      *
  1089. //      * @param c collection containing elements to be added to this queue
  1090. //      * @return {@code true} if this queue changed as a result of the call
  1091. //      * @throws ClassCastException
  1092. //      * @throws NullPointerException
  1093. //      * @throws IllegalArgumentException
  1094. //      * @throws IllegalStateException
  1095. //      * @see #add(Object)
  1096. //      */
  1097. //     public boolean addAll(Collection<? extends E> c) {
  1098. //         if (c == null)
  1099. //             throw new NullPointerException();
  1100. //         if (c == this)
  1101. //             throw new IllegalArgumentException();
  1102. //         final ReentrantLock lock = this.lock;
  1103. //         lock.lock();
  1104. //         try {
  1105. //             boolean modified = false;
  1106. //             for (E e : c)
  1107. //                 if (linkLast(e))
  1108. //                     modified = true;
  1109. //             return modified;
  1110. //         } finally {
  1111. //             lock.unlock();
  1112. //         }
  1113. //     }

  1114.     @Override
  1115.     public boolean removeFirstOccurrence(final Object o) {
  1116.         if (o == null) {
  1117.             return false;
  1118.         }
  1119.         lock.lock();
  1120.         try {
  1121.             for (Node<E> p = first; p != null; p = p.next) {
  1122.                 if (o.equals(p.item)) {
  1123.                     unlink(p);
  1124.                     return true;
  1125.                 }
  1126.             }
  1127.             return false;
  1128.         } finally {
  1129.             lock.unlock();
  1130.         }
  1131.     }

  1132.     /**
  1133.      * {@inheritDoc}
  1134.      */
  1135.     @Override
  1136.     public E removeLast() {
  1137.         final E x = pollLast();
  1138.         if (x == null) {
  1139.             throw new NoSuchElementException();
  1140.         }
  1141.         return x;
  1142.     }

  1143.     @Override
  1144.     public boolean removeLastOccurrence(final Object o) {
  1145.         if (o == null) {
  1146.             return false;
  1147.         }
  1148.         lock.lock();
  1149.         try {
  1150.             for (Node<E> p = last; p != null; p = p.prev) {
  1151.                 if (o.equals(p.item)) {
  1152.                     unlink(p);
  1153.                     return true;
  1154.                 }
  1155.             }
  1156.             return false;
  1157.         } finally {
  1158.             lock.unlock();
  1159.         }
  1160.     }

  1161.     /**
  1162.      * Returns the number of elements in this deque.
  1163.      *
  1164.      * @return the number of elements in this deque
  1165.      */
  1166.     @Override
  1167.     public int size() {
  1168.         lock.lock();
  1169.         try {
  1170.             return count;
  1171.         } finally {
  1172.             lock.unlock();
  1173.         }
  1174.     }

  1175.     /**
  1176.      * Unlinks the first element in the queue, waiting until there is an element
  1177.      * to unlink if the queue is empty.
  1178.      *
  1179.      * <p>
  1180.      * This method is equivalent to {@link #takeFirst()}.
  1181.      * </p>
  1182.      *
  1183.      * @return the unlinked element
  1184.      * @throws InterruptedException if the current thread is interrupted
  1185.      */
  1186.     public E take() throws InterruptedException {
  1187.         return takeFirst();
  1188.     }

  1189.     /**
  1190.      * Unlinks the first element in the queue, waiting until there is an element
  1191.      * to unlink if the queue is empty.
  1192.      *
  1193.      * @return the unlinked element
  1194.      * @throws InterruptedException if the current thread is interrupted
  1195.      */
  1196.     public E takeFirst() throws InterruptedException {
  1197.         lock.lock();
  1198.         try {
  1199.             E x;
  1200.             while ((x = unlinkFirst()) == null) {
  1201.                 notEmpty.await();
  1202.             }
  1203.             return x;
  1204.         } finally {
  1205.             lock.unlock();
  1206.         }
  1207.     }

  1208.     /**
  1209.      * Unlinks the last element in the queue, waiting until there is an element
  1210.      * to unlink if the queue is empty.
  1211.      *
  1212.      * @return the unlinked element
  1213.      * @throws InterruptedException if the current thread is interrupted
  1214.      */
  1215.     public E takeLast() throws InterruptedException {
  1216.         lock.lock();
  1217.         try {
  1218.             E x;
  1219.             while ((x = unlinkLast()) == null) {
  1220.                 notEmpty.await();
  1221.             }
  1222.             return x;
  1223.         } finally {
  1224.             lock.unlock();
  1225.         }
  1226.     }

  1227.     /**
  1228.      * Returns an array containing all of the elements in this deque, in
  1229.      * proper sequence (from first to last element).
  1230.      *
  1231.      * <p>
  1232.      * The returned array will be "safe" in that no references to it are
  1233.      * maintained by this deque.  (In other words, this method must allocate
  1234.      * a new array).  The caller is thus free to modify the returned array.
  1235.      * </p>
  1236.      * <p>
  1237.      * This method acts as bridge between array-based and collection-based
  1238.      * APIs.
  1239.      * </p>
  1240.      *
  1241.      * @return an array containing all of the elements in this deque
  1242.      */
  1243.     @Override
  1244.     public Object[] toArray() {
  1245.         lock.lock();
  1246.         try {
  1247.             final Object[] a = new Object[count];
  1248.             int k = 0;
  1249.             for (Node<E> p = first; p != null; p = p.next) {
  1250.                 a[k++] = p.item;
  1251.             }
  1252.             return a;
  1253.         } finally {
  1254.             lock.unlock();
  1255.         }
  1256.     }

  1257.     /**
  1258.      * {@inheritDoc}
  1259.      */
  1260.     @SuppressWarnings("unchecked")
  1261.     @Override
  1262.     public <T> T[] toArray(T[] a) {
  1263.         lock.lock();
  1264.         try {
  1265.             if (a.length < count) {
  1266.                 a = (T[])java.lang.reflect.Array.newInstance
  1267.                     (a.getClass().getComponentType(), count);
  1268.             }
  1269.             int k = 0;
  1270.             for (Node<E> p = first; p != null; p = p.next) {
  1271.                 a[k++] = (T)p.item;
  1272.             }
  1273.             if (a.length > k) {
  1274.                 a[k] = null;
  1275.             }
  1276.             return a;
  1277.         } finally {
  1278.             lock.unlock();
  1279.         }
  1280.     }

  1281.     @Override
  1282.     public String toString() {
  1283.         lock.lock();
  1284.         try {
  1285.             return super.toString();
  1286.         } finally {
  1287.             lock.unlock();
  1288.         }
  1289.     }

  1290.     /**
  1291.      * Unlinks the provided node.
  1292.      *
  1293.      * @param x The node to unlink
  1294.      */
  1295.     private void unlink(final Node<E> x) {
  1296.         // assert lock.isHeldByCurrentThread();
  1297.         final Node<E> p = x.prev;
  1298.         final Node<E> n = x.next;
  1299.         if (p == null) {
  1300.             unlinkFirst();
  1301.         } else if (n == null) {
  1302.             unlinkLast();
  1303.         } else {
  1304.             p.next = n;
  1305.             n.prev = p;
  1306.             x.item = null;
  1307.             // Don't mess with x's links.  They may still be in use by
  1308.             // an iterator.
  1309.         --count;
  1310.             notFull.signal();
  1311.         }
  1312.     }

  1313.     // Monitoring methods

  1314.     /**
  1315.      * Removes and returns the first element, or null if empty.
  1316.      *
  1317.      * @return The first element or {@code null} if empty
  1318.      */
  1319.     private E unlinkFirst() {
  1320.         // assert lock.isHeldByCurrentThread();
  1321.         final Node<E> f = first;
  1322.         if (f == null) {
  1323.             return null;
  1324.         }
  1325.         final Node<E> n = f.next;
  1326.         final E item = f.item;
  1327.         f.item = null;
  1328.         f.next = f; // help GC
  1329.         first = n;
  1330.         if (n == null) {
  1331.             last = null;
  1332.         } else {
  1333.             n.prev = null;
  1334.         }
  1335.         --count;
  1336.         notFull.signal();
  1337.         return item;
  1338.     }

  1339.     /**
  1340.      * Removes and returns the last element, or null if empty.
  1341.      *
  1342.      * @return The first element or {@code null} if empty
  1343.      */
  1344.     private E unlinkLast() {
  1345.         // assert lock.isHeldByCurrentThread();
  1346.         final Node<E> l = last;
  1347.         if (l == null) {
  1348.             return null;
  1349.         }
  1350.         final Node<E> p = l.prev;
  1351.         final E item = l.item;
  1352.         l.item = null;
  1353.         l.prev = l; // help GC
  1354.         last = p;
  1355.         if (p == null) {
  1356.             first = null;
  1357.         } else {
  1358.             p.next = null;
  1359.         }
  1360.         --count;
  1361.         notFull.signal();
  1362.         return item;
  1363.     }

  1364.     /**
  1365.      * Saves the state of this deque to a stream (that is, serialize it).
  1366.      *
  1367.      * @serialData The capacity (int), followed by elements (each an
  1368.      * {@code Object}) in the proper order, followed by a null
  1369.      * @param s the stream
  1370.      * @throws  IOException if I/O errors occur while writing to the underlying {@code OutputStream}
  1371.      */
  1372.     private void writeObject(final java.io.ObjectOutputStream s) throws IOException {
  1373.         lock.lock();
  1374.         try {
  1375.             // Write out capacity and any hidden stuff
  1376.             s.defaultWriteObject();
  1377.             // Write out all elements in the proper order.
  1378.             for (Node<E> p = first; p != null; p = p.next) {
  1379.                 s.writeObject(p.item);
  1380.             }
  1381.             // Use trailing null as sentinel
  1382.             s.writeObject(null);
  1383.         } finally {
  1384.             lock.unlock();
  1385.         }
  1386.     }
  1387. }