rt/emul/compact/src/main/java/java/util/concurrent/DelayQueue.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
jaroslav@1890
    37
package java.util.concurrent;
jaroslav@1890
    38
import java.util.concurrent.locks.*;
jaroslav@1890
    39
import java.util.*;
jaroslav@1890
    40
jaroslav@1890
    41
/**
jaroslav@1890
    42
 * An unbounded {@linkplain BlockingQueue blocking queue} of
jaroslav@1890
    43
 * <tt>Delayed</tt> elements, in which an element can only be taken
jaroslav@1890
    44
 * when its delay has expired.  The <em>head</em> of the queue is that
jaroslav@1890
    45
 * <tt>Delayed</tt> element whose delay expired furthest in the
jaroslav@1890
    46
 * past.  If no delay has expired there is no head and <tt>poll</tt>
jaroslav@1890
    47
 * will return <tt>null</tt>. Expiration occurs when an element's
jaroslav@1890
    48
 * <tt>getDelay(TimeUnit.NANOSECONDS)</tt> method returns a value less
jaroslav@1890
    49
 * than or equal to zero.  Even though unexpired elements cannot be
jaroslav@1890
    50
 * removed using <tt>take</tt> or <tt>poll</tt>, they are otherwise
jaroslav@1890
    51
 * treated as normal elements. For example, the <tt>size</tt> method
jaroslav@1890
    52
 * returns the count of both expired and unexpired elements.
jaroslav@1890
    53
 * This queue does not permit null elements.
jaroslav@1890
    54
 *
jaroslav@1890
    55
 * <p>This class and its iterator implement all of the
jaroslav@1890
    56
 * <em>optional</em> methods of the {@link Collection} and {@link
jaroslav@1890
    57
 * Iterator} interfaces.
jaroslav@1890
    58
 *
jaroslav@1890
    59
 * <p>This class is a member of the
jaroslav@1890
    60
 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
jaroslav@1890
    61
 * Java Collections Framework</a>.
jaroslav@1890
    62
 *
jaroslav@1890
    63
 * @since 1.5
jaroslav@1890
    64
 * @author Doug Lea
jaroslav@1890
    65
 * @param <E> the type of elements held in this collection
jaroslav@1890
    66
 */
jaroslav@1890
    67
jaroslav@1890
    68
public class DelayQueue<E extends Delayed> extends AbstractQueue<E>
jaroslav@1890
    69
    implements BlockingQueue<E> {
jaroslav@1890
    70
jaroslav@1890
    71
    private transient final ReentrantLock lock = new ReentrantLock();
jaroslav@1890
    72
    private final PriorityQueue<E> q = new PriorityQueue<E>();
jaroslav@1890
    73
jaroslav@1890
    74
    /**
jaroslav@1890
    75
     * Thread designated to wait for the element at the head of
jaroslav@1890
    76
     * the queue.  This variant of the Leader-Follower pattern
jaroslav@1890
    77
     * (http://www.cs.wustl.edu/~schmidt/POSA/POSA2/) serves to
jaroslav@1890
    78
     * minimize unnecessary timed waiting.  When a thread becomes
jaroslav@1890
    79
     * the leader, it waits only for the next delay to elapse, but
jaroslav@1890
    80
     * other threads await indefinitely.  The leader thread must
jaroslav@1890
    81
     * signal some other thread before returning from take() or
jaroslav@1890
    82
     * poll(...), unless some other thread becomes leader in the
jaroslav@1890
    83
     * interim.  Whenever the head of the queue is replaced with
jaroslav@1890
    84
     * an element with an earlier expiration time, the leader
jaroslav@1890
    85
     * field is invalidated by being reset to null, and some
jaroslav@1890
    86
     * waiting thread, but not necessarily the current leader, is
jaroslav@1890
    87
     * signalled.  So waiting threads must be prepared to acquire
jaroslav@1890
    88
     * and lose leadership while waiting.
jaroslav@1890
    89
     */
jaroslav@1890
    90
    private Thread leader = null;
jaroslav@1890
    91
jaroslav@1890
    92
    /**
jaroslav@1890
    93
     * Condition signalled when a newer element becomes available
jaroslav@1890
    94
     * at the head of the queue or a new thread may need to
jaroslav@1890
    95
     * become leader.
jaroslav@1890
    96
     */
jaroslav@1890
    97
    private final Condition available = lock.newCondition();
jaroslav@1890
    98
jaroslav@1890
    99
    /**
jaroslav@1890
   100
     * Creates a new <tt>DelayQueue</tt> that is initially empty.
jaroslav@1890
   101
     */
jaroslav@1890
   102
    public DelayQueue() {}
jaroslav@1890
   103
jaroslav@1890
   104
    /**
jaroslav@1890
   105
     * Creates a <tt>DelayQueue</tt> initially containing the elements of the
jaroslav@1890
   106
     * given collection of {@link Delayed} instances.
jaroslav@1890
   107
     *
jaroslav@1890
   108
     * @param c the collection of elements to initially contain
jaroslav@1890
   109
     * @throws NullPointerException if the specified collection or any
jaroslav@1890
   110
     *         of its elements are null
jaroslav@1890
   111
     */
jaroslav@1890
   112
    public DelayQueue(Collection<? extends E> c) {
jaroslav@1890
   113
        this.addAll(c);
jaroslav@1890
   114
    }
jaroslav@1890
   115
jaroslav@1890
   116
    /**
jaroslav@1890
   117
     * Inserts the specified element into this delay queue.
jaroslav@1890
   118
     *
jaroslav@1890
   119
     * @param e the element to add
jaroslav@1890
   120
     * @return <tt>true</tt> (as specified by {@link Collection#add})
jaroslav@1890
   121
     * @throws NullPointerException if the specified element is null
jaroslav@1890
   122
     */
jaroslav@1890
   123
    public boolean add(E e) {
jaroslav@1890
   124
        return offer(e);
jaroslav@1890
   125
    }
jaroslav@1890
   126
jaroslav@1890
   127
    /**
jaroslav@1890
   128
     * Inserts the specified element into this delay queue.
jaroslav@1890
   129
     *
jaroslav@1890
   130
     * @param e the element to add
jaroslav@1890
   131
     * @return <tt>true</tt>
jaroslav@1890
   132
     * @throws NullPointerException if the specified element is null
jaroslav@1890
   133
     */
jaroslav@1890
   134
    public boolean offer(E e) {
jaroslav@1890
   135
        final ReentrantLock lock = this.lock;
jaroslav@1890
   136
        lock.lock();
jaroslav@1890
   137
        try {
jaroslav@1890
   138
            q.offer(e);
jaroslav@1890
   139
            if (q.peek() == e) {
jaroslav@1890
   140
                leader = null;
jaroslav@1890
   141
                available.signal();
jaroslav@1890
   142
            }
jaroslav@1890
   143
            return true;
jaroslav@1890
   144
        } finally {
jaroslav@1890
   145
            lock.unlock();
jaroslav@1890
   146
        }
jaroslav@1890
   147
    }
jaroslav@1890
   148
jaroslav@1890
   149
    /**
jaroslav@1890
   150
     * Inserts the specified element into this delay queue. As the queue is
jaroslav@1890
   151
     * unbounded this method will never block.
jaroslav@1890
   152
     *
jaroslav@1890
   153
     * @param e the element to add
jaroslav@1890
   154
     * @throws NullPointerException {@inheritDoc}
jaroslav@1890
   155
     */
jaroslav@1890
   156
    public void put(E e) {
jaroslav@1890
   157
        offer(e);
jaroslav@1890
   158
    }
jaroslav@1890
   159
jaroslav@1890
   160
    /**
jaroslav@1890
   161
     * Inserts the specified element into this delay queue. As the queue is
jaroslav@1890
   162
     * unbounded this method will never block.
jaroslav@1890
   163
     *
jaroslav@1890
   164
     * @param e the element to add
jaroslav@1890
   165
     * @param timeout This parameter is ignored as the method never blocks
jaroslav@1890
   166
     * @param unit This parameter is ignored as the method never blocks
jaroslav@1890
   167
     * @return <tt>true</tt>
jaroslav@1890
   168
     * @throws NullPointerException {@inheritDoc}
jaroslav@1890
   169
     */
jaroslav@1890
   170
    public boolean offer(E e, long timeout, TimeUnit unit) {
jaroslav@1890
   171
        return offer(e);
jaroslav@1890
   172
    }
jaroslav@1890
   173
jaroslav@1890
   174
    /**
jaroslav@1890
   175
     * Retrieves and removes the head of this queue, or returns <tt>null</tt>
jaroslav@1890
   176
     * if this queue has no elements with an expired delay.
jaroslav@1890
   177
     *
jaroslav@1890
   178
     * @return the head of this queue, or <tt>null</tt> if this
jaroslav@1890
   179
     *         queue has no elements with an expired delay
jaroslav@1890
   180
     */
jaroslav@1890
   181
    public E poll() {
jaroslav@1890
   182
        final ReentrantLock lock = this.lock;
jaroslav@1890
   183
        lock.lock();
jaroslav@1890
   184
        try {
jaroslav@1890
   185
            E first = q.peek();
jaroslav@1890
   186
            if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
jaroslav@1890
   187
                return null;
jaroslav@1890
   188
            else
jaroslav@1890
   189
                return q.poll();
jaroslav@1890
   190
        } finally {
jaroslav@1890
   191
            lock.unlock();
jaroslav@1890
   192
        }
jaroslav@1890
   193
    }
jaroslav@1890
   194
jaroslav@1890
   195
    /**
jaroslav@1890
   196
     * Retrieves and removes the head of this queue, waiting if necessary
jaroslav@1890
   197
     * until an element with an expired delay is available on this queue.
jaroslav@1890
   198
     *
jaroslav@1890
   199
     * @return the head of this queue
jaroslav@1890
   200
     * @throws InterruptedException {@inheritDoc}
jaroslav@1890
   201
     */
jaroslav@1890
   202
    public E take() throws InterruptedException {
jaroslav@1890
   203
        final ReentrantLock lock = this.lock;
jaroslav@1890
   204
        lock.lockInterruptibly();
jaroslav@1890
   205
        try {
jaroslav@1890
   206
            for (;;) {
jaroslav@1890
   207
                E first = q.peek();
jaroslav@1890
   208
                if (first == null)
jaroslav@1890
   209
                    available.await();
jaroslav@1890
   210
                else {
jaroslav@1890
   211
                    long delay = first.getDelay(TimeUnit.NANOSECONDS);
jaroslav@1890
   212
                    if (delay <= 0)
jaroslav@1890
   213
                        return q.poll();
jaroslav@1890
   214
                    else if (leader != null)
jaroslav@1890
   215
                        available.await();
jaroslav@1890
   216
                    else {
jaroslav@1890
   217
                        Thread thisThread = Thread.currentThread();
jaroslav@1890
   218
                        leader = thisThread;
jaroslav@1890
   219
                        try {
jaroslav@1890
   220
                            available.awaitNanos(delay);
jaroslav@1890
   221
                        } finally {
jaroslav@1890
   222
                            if (leader == thisThread)
jaroslav@1890
   223
                                leader = null;
jaroslav@1890
   224
                        }
jaroslav@1890
   225
                    }
jaroslav@1890
   226
                }
jaroslav@1890
   227
            }
jaroslav@1890
   228
        } finally {
jaroslav@1890
   229
            if (leader == null && q.peek() != null)
jaroslav@1890
   230
                available.signal();
jaroslav@1890
   231
            lock.unlock();
jaroslav@1890
   232
        }
jaroslav@1890
   233
    }
jaroslav@1890
   234
jaroslav@1890
   235
    /**
jaroslav@1890
   236
     * Retrieves and removes the head of this queue, waiting if necessary
jaroslav@1890
   237
     * until an element with an expired delay is available on this queue,
jaroslav@1890
   238
     * or the specified wait time expires.
jaroslav@1890
   239
     *
jaroslav@1890
   240
     * @return the head of this queue, or <tt>null</tt> if the
jaroslav@1890
   241
     *         specified waiting time elapses before an element with
jaroslav@1890
   242
     *         an expired delay becomes available
jaroslav@1890
   243
     * @throws InterruptedException {@inheritDoc}
jaroslav@1890
   244
     */
jaroslav@1890
   245
    public E poll(long timeout, TimeUnit unit) throws InterruptedException {
jaroslav@1890
   246
        long nanos = unit.toNanos(timeout);
jaroslav@1890
   247
        final ReentrantLock lock = this.lock;
jaroslav@1890
   248
        lock.lockInterruptibly();
jaroslav@1890
   249
        try {
jaroslav@1890
   250
            for (;;) {
jaroslav@1890
   251
                E first = q.peek();
jaroslav@1890
   252
                if (first == null) {
jaroslav@1890
   253
                    if (nanos <= 0)
jaroslav@1890
   254
                        return null;
jaroslav@1890
   255
                    else
jaroslav@1890
   256
                        nanos = available.awaitNanos(nanos);
jaroslav@1890
   257
                } else {
jaroslav@1890
   258
                    long delay = first.getDelay(TimeUnit.NANOSECONDS);
jaroslav@1890
   259
                    if (delay <= 0)
jaroslav@1890
   260
                        return q.poll();
jaroslav@1890
   261
                    if (nanos <= 0)
jaroslav@1890
   262
                        return null;
jaroslav@1890
   263
                    if (nanos < delay || leader != null)
jaroslav@1890
   264
                        nanos = available.awaitNanos(nanos);
jaroslav@1890
   265
                    else {
jaroslav@1890
   266
                        Thread thisThread = Thread.currentThread();
jaroslav@1890
   267
                        leader = thisThread;
jaroslav@1890
   268
                        try {
jaroslav@1890
   269
                            long timeLeft = available.awaitNanos(delay);
jaroslav@1890
   270
                            nanos -= delay - timeLeft;
jaroslav@1890
   271
                        } finally {
jaroslav@1890
   272
                            if (leader == thisThread)
jaroslav@1890
   273
                                leader = null;
jaroslav@1890
   274
                        }
jaroslav@1890
   275
                    }
jaroslav@1890
   276
                }
jaroslav@1890
   277
            }
jaroslav@1890
   278
        } finally {
jaroslav@1890
   279
            if (leader == null && q.peek() != null)
jaroslav@1890
   280
                available.signal();
jaroslav@1890
   281
            lock.unlock();
jaroslav@1890
   282
        }
jaroslav@1890
   283
    }
jaroslav@1890
   284
jaroslav@1890
   285
    /**
jaroslav@1890
   286
     * Retrieves, but does not remove, the head of this queue, or
jaroslav@1890
   287
     * returns <tt>null</tt> if this queue is empty.  Unlike
jaroslav@1890
   288
     * <tt>poll</tt>, if no expired elements are available in the queue,
jaroslav@1890
   289
     * this method returns the element that will expire next,
jaroslav@1890
   290
     * if one exists.
jaroslav@1890
   291
     *
jaroslav@1890
   292
     * @return the head of this queue, or <tt>null</tt> if this
jaroslav@1890
   293
     *         queue is empty.
jaroslav@1890
   294
     */
jaroslav@1890
   295
    public E peek() {
jaroslav@1890
   296
        final ReentrantLock lock = this.lock;
jaroslav@1890
   297
        lock.lock();
jaroslav@1890
   298
        try {
jaroslav@1890
   299
            return q.peek();
jaroslav@1890
   300
        } finally {
jaroslav@1890
   301
            lock.unlock();
jaroslav@1890
   302
        }
jaroslav@1890
   303
    }
jaroslav@1890
   304
jaroslav@1890
   305
    public int size() {
jaroslav@1890
   306
        final ReentrantLock lock = this.lock;
jaroslav@1890
   307
        lock.lock();
jaroslav@1890
   308
        try {
jaroslav@1890
   309
            return q.size();
jaroslav@1890
   310
        } finally {
jaroslav@1890
   311
            lock.unlock();
jaroslav@1890
   312
        }
jaroslav@1890
   313
    }
jaroslav@1890
   314
jaroslav@1890
   315
    /**
jaroslav@1890
   316
     * @throws UnsupportedOperationException {@inheritDoc}
jaroslav@1890
   317
     * @throws ClassCastException            {@inheritDoc}
jaroslav@1890
   318
     * @throws NullPointerException          {@inheritDoc}
jaroslav@1890
   319
     * @throws IllegalArgumentException      {@inheritDoc}
jaroslav@1890
   320
     */
jaroslav@1890
   321
    public int drainTo(Collection<? super E> c) {
jaroslav@1890
   322
        if (c == null)
jaroslav@1890
   323
            throw new NullPointerException();
jaroslav@1890
   324
        if (c == this)
jaroslav@1890
   325
            throw new IllegalArgumentException();
jaroslav@1890
   326
        final ReentrantLock lock = this.lock;
jaroslav@1890
   327
        lock.lock();
jaroslav@1890
   328
        try {
jaroslav@1890
   329
            int n = 0;
jaroslav@1890
   330
            for (;;) {
jaroslav@1890
   331
                E first = q.peek();
jaroslav@1890
   332
                if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
jaroslav@1890
   333
                    break;
jaroslav@1890
   334
                c.add(q.poll());
jaroslav@1890
   335
                ++n;
jaroslav@1890
   336
            }
jaroslav@1890
   337
            return n;
jaroslav@1890
   338
        } finally {
jaroslav@1890
   339
            lock.unlock();
jaroslav@1890
   340
        }
jaroslav@1890
   341
    }
jaroslav@1890
   342
jaroslav@1890
   343
    /**
jaroslav@1890
   344
     * @throws UnsupportedOperationException {@inheritDoc}
jaroslav@1890
   345
     * @throws ClassCastException            {@inheritDoc}
jaroslav@1890
   346
     * @throws NullPointerException          {@inheritDoc}
jaroslav@1890
   347
     * @throws IllegalArgumentException      {@inheritDoc}
jaroslav@1890
   348
     */
jaroslav@1890
   349
    public int drainTo(Collection<? super E> c, int maxElements) {
jaroslav@1890
   350
        if (c == null)
jaroslav@1890
   351
            throw new NullPointerException();
jaroslav@1890
   352
        if (c == this)
jaroslav@1890
   353
            throw new IllegalArgumentException();
jaroslav@1890
   354
        if (maxElements <= 0)
jaroslav@1890
   355
            return 0;
jaroslav@1890
   356
        final ReentrantLock lock = this.lock;
jaroslav@1890
   357
        lock.lock();
jaroslav@1890
   358
        try {
jaroslav@1890
   359
            int n = 0;
jaroslav@1890
   360
            while (n < maxElements) {
jaroslav@1890
   361
                E first = q.peek();
jaroslav@1890
   362
                if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
jaroslav@1890
   363
                    break;
jaroslav@1890
   364
                c.add(q.poll());
jaroslav@1890
   365
                ++n;
jaroslav@1890
   366
            }
jaroslav@1890
   367
            return n;
jaroslav@1890
   368
        } finally {
jaroslav@1890
   369
            lock.unlock();
jaroslav@1890
   370
        }
jaroslav@1890
   371
    }
jaroslav@1890
   372
jaroslav@1890
   373
    /**
jaroslav@1890
   374
     * Atomically removes all of the elements from this delay queue.
jaroslav@1890
   375
     * The queue will be empty after this call returns.
jaroslav@1890
   376
     * Elements with an unexpired delay are not waited for; they are
jaroslav@1890
   377
     * simply discarded from the queue.
jaroslav@1890
   378
     */
jaroslav@1890
   379
    public void clear() {
jaroslav@1890
   380
        final ReentrantLock lock = this.lock;
jaroslav@1890
   381
        lock.lock();
jaroslav@1890
   382
        try {
jaroslav@1890
   383
            q.clear();
jaroslav@1890
   384
        } finally {
jaroslav@1890
   385
            lock.unlock();
jaroslav@1890
   386
        }
jaroslav@1890
   387
    }
jaroslav@1890
   388
jaroslav@1890
   389
    /**
jaroslav@1890
   390
     * Always returns <tt>Integer.MAX_VALUE</tt> because
jaroslav@1890
   391
     * a <tt>DelayQueue</tt> is not capacity constrained.
jaroslav@1890
   392
     *
jaroslav@1890
   393
     * @return <tt>Integer.MAX_VALUE</tt>
jaroslav@1890
   394
     */
jaroslav@1890
   395
    public int remainingCapacity() {
jaroslav@1890
   396
        return Integer.MAX_VALUE;
jaroslav@1890
   397
    }
jaroslav@1890
   398
jaroslav@1890
   399
    /**
jaroslav@1890
   400
     * Returns an array containing all of the elements in this queue.
jaroslav@1890
   401
     * The returned array elements are in no particular order.
jaroslav@1890
   402
     *
jaroslav@1890
   403
     * <p>The returned array will be "safe" in that no references to it are
jaroslav@1890
   404
     * maintained by this queue.  (In other words, this method must allocate
jaroslav@1890
   405
     * a new array).  The caller is thus free to modify the returned array.
jaroslav@1890
   406
     *
jaroslav@1890
   407
     * <p>This method acts as bridge between array-based and collection-based
jaroslav@1890
   408
     * APIs.
jaroslav@1890
   409
     *
jaroslav@1890
   410
     * @return an array containing all of the elements in this queue
jaroslav@1890
   411
     */
jaroslav@1890
   412
    public Object[] toArray() {
jaroslav@1890
   413
        final ReentrantLock lock = this.lock;
jaroslav@1890
   414
        lock.lock();
jaroslav@1890
   415
        try {
jaroslav@1890
   416
            return q.toArray();
jaroslav@1890
   417
        } finally {
jaroslav@1890
   418
            lock.unlock();
jaroslav@1890
   419
        }
jaroslav@1890
   420
    }
jaroslav@1890
   421
jaroslav@1890
   422
    /**
jaroslav@1890
   423
     * Returns an array containing all of the elements in this queue; the
jaroslav@1890
   424
     * runtime type of the returned array is that of the specified array.
jaroslav@1890
   425
     * The returned array elements are in no particular order.
jaroslav@1890
   426
     * If the queue fits in the specified array, it is returned therein.
jaroslav@1890
   427
     * Otherwise, a new array is allocated with the runtime type of the
jaroslav@1890
   428
     * specified array and the size of this queue.
jaroslav@1890
   429
     *
jaroslav@1890
   430
     * <p>If this queue fits in the specified array with room to spare
jaroslav@1890
   431
     * (i.e., the array has more elements than this queue), the element in
jaroslav@1890
   432
     * the array immediately following the end of the queue is set to
jaroslav@1890
   433
     * <tt>null</tt>.
jaroslav@1890
   434
     *
jaroslav@1890
   435
     * <p>Like the {@link #toArray()} method, this method acts as bridge between
jaroslav@1890
   436
     * array-based and collection-based APIs.  Further, this method allows
jaroslav@1890
   437
     * precise control over the runtime type of the output array, and may,
jaroslav@1890
   438
     * under certain circumstances, be used to save allocation costs.
jaroslav@1890
   439
     *
jaroslav@1890
   440
     * <p>The following code can be used to dump a delay queue into a newly
jaroslav@1890
   441
     * allocated array of <tt>Delayed</tt>:
jaroslav@1890
   442
     *
jaroslav@1890
   443
     * <pre>
jaroslav@1890
   444
     *     Delayed[] a = q.toArray(new Delayed[0]);</pre>
jaroslav@1890
   445
     *
jaroslav@1890
   446
     * Note that <tt>toArray(new Object[0])</tt> is identical in function to
jaroslav@1890
   447
     * <tt>toArray()</tt>.
jaroslav@1890
   448
     *
jaroslav@1890
   449
     * @param a the array into which the elements of the queue are to
jaroslav@1890
   450
     *          be stored, if it is big enough; otherwise, a new array of the
jaroslav@1890
   451
     *          same runtime type is allocated for this purpose
jaroslav@1890
   452
     * @return an array containing all of the elements in this queue
jaroslav@1890
   453
     * @throws ArrayStoreException if the runtime type of the specified array
jaroslav@1890
   454
     *         is not a supertype of the runtime type of every element in
jaroslav@1890
   455
     *         this queue
jaroslav@1890
   456
     * @throws NullPointerException if the specified array is null
jaroslav@1890
   457
     */
jaroslav@1890
   458
    public <T> T[] toArray(T[] a) {
jaroslav@1890
   459
        final ReentrantLock lock = this.lock;
jaroslav@1890
   460
        lock.lock();
jaroslav@1890
   461
        try {
jaroslav@1890
   462
            return q.toArray(a);
jaroslav@1890
   463
        } finally {
jaroslav@1890
   464
            lock.unlock();
jaroslav@1890
   465
        }
jaroslav@1890
   466
    }
jaroslav@1890
   467
jaroslav@1890
   468
    /**
jaroslav@1890
   469
     * Removes a single instance of the specified element from this
jaroslav@1890
   470
     * queue, if it is present, whether or not it has expired.
jaroslav@1890
   471
     */
jaroslav@1890
   472
    public boolean remove(Object o) {
jaroslav@1890
   473
        final ReentrantLock lock = this.lock;
jaroslav@1890
   474
        lock.lock();
jaroslav@1890
   475
        try {
jaroslav@1890
   476
            return q.remove(o);
jaroslav@1890
   477
        } finally {
jaroslav@1890
   478
            lock.unlock();
jaroslav@1890
   479
        }
jaroslav@1890
   480
    }
jaroslav@1890
   481
jaroslav@1890
   482
    /**
jaroslav@1890
   483
     * Returns an iterator over all the elements (both expired and
jaroslav@1890
   484
     * unexpired) in this queue. The iterator does not return the
jaroslav@1890
   485
     * elements in any particular order.
jaroslav@1890
   486
     *
jaroslav@1890
   487
     * <p>The returned iterator is a "weakly consistent" iterator that
jaroslav@1890
   488
     * will never throw {@link java.util.ConcurrentModificationException
jaroslav@1890
   489
     * ConcurrentModificationException}, and guarantees to traverse
jaroslav@1890
   490
     * elements as they existed upon construction of the iterator, and
jaroslav@1890
   491
     * may (but is not guaranteed to) reflect any modifications
jaroslav@1890
   492
     * subsequent to construction.
jaroslav@1890
   493
     *
jaroslav@1890
   494
     * @return an iterator over the elements in this queue
jaroslav@1890
   495
     */
jaroslav@1890
   496
    public Iterator<E> iterator() {
jaroslav@1890
   497
        return new Itr(toArray());
jaroslav@1890
   498
    }
jaroslav@1890
   499
jaroslav@1890
   500
    /**
jaroslav@1890
   501
     * Snapshot iterator that works off copy of underlying q array.
jaroslav@1890
   502
     */
jaroslav@1890
   503
    private class Itr implements Iterator<E> {
jaroslav@1890
   504
        final Object[] array; // Array of all elements
jaroslav@1890
   505
        int cursor;           // index of next element to return;
jaroslav@1890
   506
        int lastRet;          // index of last element, or -1 if no such
jaroslav@1890
   507
jaroslav@1890
   508
        Itr(Object[] array) {
jaroslav@1890
   509
            lastRet = -1;
jaroslav@1890
   510
            this.array = array;
jaroslav@1890
   511
        }
jaroslav@1890
   512
jaroslav@1890
   513
        public boolean hasNext() {
jaroslav@1890
   514
            return cursor < array.length;
jaroslav@1890
   515
        }
jaroslav@1890
   516
jaroslav@1890
   517
        @SuppressWarnings("unchecked")
jaroslav@1890
   518
        public E next() {
jaroslav@1890
   519
            if (cursor >= array.length)
jaroslav@1890
   520
                throw new NoSuchElementException();
jaroslav@1890
   521
            lastRet = cursor;
jaroslav@1890
   522
            return (E)array[cursor++];
jaroslav@1890
   523
        }
jaroslav@1890
   524
jaroslav@1890
   525
        public void remove() {
jaroslav@1890
   526
            if (lastRet < 0)
jaroslav@1890
   527
                throw new IllegalStateException();
jaroslav@1890
   528
            Object x = array[lastRet];
jaroslav@1890
   529
            lastRet = -1;
jaroslav@1890
   530
            // Traverse underlying queue to find == element,
jaroslav@1890
   531
            // not just a .equals element.
jaroslav@1890
   532
            lock.lock();
jaroslav@1890
   533
            try {
jaroslav@1890
   534
                for (Iterator it = q.iterator(); it.hasNext(); ) {
jaroslav@1890
   535
                    if (it.next() == x) {
jaroslav@1890
   536
                        it.remove();
jaroslav@1890
   537
                        return;
jaroslav@1890
   538
                    }
jaroslav@1890
   539
                }
jaroslav@1890
   540
            } finally {
jaroslav@1890
   541
                lock.unlock();
jaroslav@1890
   542
            }
jaroslav@1890
   543
        }
jaroslav@1890
   544
    }
jaroslav@1890
   545
jaroslav@1890
   546
}