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