0N/A/*
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/A/*
0N/A * This file is available under and governed by the GNU General Public
0N/A * License version 2 only, as published by the Free Software Foundation.
0N/A * However, the following notice accompanied the original version of this
0N/A * file:
0N/A *
0N/A * Written by Doug Lea with assistance from members of JCP JSR-166
0N/A * Expert Group and released to the public domain, as explained at
3984N/A * http://creativecommons.org/publicdomain/zero/1.0/
0N/A */
0N/A
0N/A
0N/Apackage java.util.concurrent;
0N/Aimport java.util.concurrent.locks.*;
0N/Aimport java.util.*;
0N/A
0N/A/**
0N/A * An unbounded {@linkplain BlockingQueue blocking queue} of
0N/A * <tt>Delayed</tt> elements, in which an element can only be taken
0N/A * when its delay has expired. The <em>head</em> of the queue is that
0N/A * <tt>Delayed</tt> element whose delay expired furthest in the
0N/A * past. If no delay has expired there is no head and <tt>poll</tt>
0N/A * will return <tt>null</tt>. Expiration occurs when an element's
0N/A * <tt>getDelay(TimeUnit.NANOSECONDS)</tt> method returns a value less
0N/A * than or equal to zero. Even though unexpired elements cannot be
0N/A * removed using <tt>take</tt> or <tt>poll</tt>, they are otherwise
0N/A * treated as normal elements. For example, the <tt>size</tt> method
0N/A * returns the count of both expired and unexpired elements.
0N/A * This queue does not permit null elements.
0N/A *
0N/A * <p>This class and its iterator implement all of the
0N/A * <em>optional</em> methods of the {@link Collection} and {@link
0N/A * Iterator} interfaces.
0N/A *
0N/A * <p>This class is a member of the
0N/A * <a href="{@docRoot}/../technotes/guides/collections/index.html">
0N/A * Java Collections Framework</a>.
0N/A *
0N/A * @since 1.5
0N/A * @author Doug Lea
0N/A * @param <E> the type of elements held in this collection
0N/A */
0N/A
0N/Apublic class DelayQueue<E extends Delayed> extends AbstractQueue<E>
0N/A implements BlockingQueue<E> {
0N/A
0N/A private transient final ReentrantLock lock = new ReentrantLock();
0N/A private final PriorityQueue<E> q = new PriorityQueue<E>();
0N/A
0N/A /**
37N/A * Thread designated to wait for the element at the head of
37N/A * the queue. This variant of the Leader-Follower pattern
37N/A * (http://www.cs.wustl.edu/~schmidt/POSA/POSA2/) serves to
37N/A * minimize unnecessary timed waiting. When a thread becomes
37N/A * the leader, it waits only for the next delay to elapse, but
37N/A * other threads await indefinitely. The leader thread must
37N/A * signal some other thread before returning from take() or
37N/A * poll(...), unless some other thread becomes leader in the
37N/A * interim. Whenever the head of the queue is replaced with
37N/A * an element with an earlier expiration time, the leader
37N/A * field is invalidated by being reset to null, and some
37N/A * waiting thread, but not necessarily the current leader, is
37N/A * signalled. So waiting threads must be prepared to acquire
37N/A * and lose leadership while waiting.
37N/A */
37N/A private Thread leader = null;
37N/A
37N/A /**
37N/A * Condition signalled when a newer element becomes available
37N/A * at the head of the queue or a new thread may need to
37N/A * become leader.
37N/A */
37N/A private final Condition available = lock.newCondition();
37N/A
37N/A /**
0N/A * Creates a new <tt>DelayQueue</tt> that is initially empty.
0N/A */
0N/A public DelayQueue() {}
0N/A
0N/A /**
0N/A * Creates a <tt>DelayQueue</tt> initially containing the elements of the
0N/A * given collection of {@link Delayed} instances.
0N/A *
0N/A * @param c the collection of elements to initially contain
0N/A * @throws NullPointerException if the specified collection or any
0N/A * of its elements are null
0N/A */
0N/A public DelayQueue(Collection<? extends E> c) {
0N/A this.addAll(c);
0N/A }
0N/A
0N/A /**
0N/A * Inserts the specified element into this delay queue.
0N/A *
0N/A * @param e the element to add
0N/A * @return <tt>true</tt> (as specified by {@link Collection#add})
0N/A * @throws NullPointerException if the specified element is null
0N/A */
0N/A public boolean add(E e) {
0N/A return offer(e);
0N/A }
0N/A
0N/A /**
0N/A * Inserts the specified element into this delay queue.
0N/A *
0N/A * @param e the element to add
0N/A * @return <tt>true</tt>
0N/A * @throws NullPointerException if the specified element is null
0N/A */
0N/A public boolean offer(E e) {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A q.offer(e);
37N/A if (q.peek() == e) {
37N/A leader = null;
37N/A available.signal();
37N/A }
0N/A return true;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Inserts the specified element into this delay queue. As the queue is
0N/A * unbounded this method will never block.
0N/A *
0N/A * @param e the element to add
0N/A * @throws NullPointerException {@inheritDoc}
0N/A */
0N/A public void put(E e) {
0N/A offer(e);
0N/A }
0N/A
0N/A /**
0N/A * Inserts the specified element into this delay queue. As the queue is
0N/A * unbounded this method will never block.
0N/A *
0N/A * @param e the element to add
0N/A * @param timeout This parameter is ignored as the method never blocks
0N/A * @param unit This parameter is ignored as the method never blocks
0N/A * @return <tt>true</tt>
0N/A * @throws NullPointerException {@inheritDoc}
0N/A */
0N/A public boolean offer(E e, long timeout, TimeUnit unit) {
0N/A return offer(e);
0N/A }
0N/A
0N/A /**
0N/A * Retrieves and removes the head of this queue, or returns <tt>null</tt>
0N/A * if this queue has no elements with an expired delay.
0N/A *
0N/A * @return the head of this queue, or <tt>null</tt> if this
0N/A * queue has no elements with an expired delay
0N/A */
0N/A public E poll() {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A E first = q.peek();
0N/A if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
0N/A return null;
37N/A else
37N/A return q.poll();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Retrieves and removes the head of this queue, waiting if necessary
0N/A * until an element with an expired delay is available on this queue.
0N/A *
0N/A * @return the head of this queue
0N/A * @throws InterruptedException {@inheritDoc}
0N/A */
0N/A public E take() throws InterruptedException {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lockInterruptibly();
0N/A try {
0N/A for (;;) {
0N/A E first = q.peek();
37N/A if (first == null)
0N/A available.await();
37N/A else {
37N/A long delay = first.getDelay(TimeUnit.NANOSECONDS);
37N/A if (delay <= 0)
37N/A return q.poll();
37N/A else if (leader != null)
37N/A available.await();
37N/A else {
37N/A Thread thisThread = Thread.currentThread();
37N/A leader = thisThread;
37N/A try {
37N/A available.awaitNanos(delay);
37N/A } finally {
37N/A if (leader == thisThread)
37N/A leader = null;
37N/A }
0N/A }
0N/A }
0N/A }
0N/A } finally {
37N/A if (leader == null && q.peek() != null)
37N/A available.signal();
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Retrieves and removes the head of this queue, waiting if necessary
0N/A * until an element with an expired delay is available on this queue,
0N/A * or the specified wait time expires.
0N/A *
0N/A * @return the head of this queue, or <tt>null</tt> if the
0N/A * specified waiting time elapses before an element with
0N/A * an expired delay becomes available
0N/A * @throws InterruptedException {@inheritDoc}
0N/A */
0N/A public E poll(long timeout, TimeUnit unit) throws InterruptedException {
0N/A long nanos = unit.toNanos(timeout);
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lockInterruptibly();
0N/A try {
0N/A for (;;) {
0N/A E first = q.peek();
0N/A if (first == null) {
0N/A if (nanos <= 0)
0N/A return null;
0N/A else
0N/A nanos = available.awaitNanos(nanos);
0N/A } else {
0N/A long delay = first.getDelay(TimeUnit.NANOSECONDS);
37N/A if (delay <= 0)
37N/A return q.poll();
37N/A if (nanos <= 0)
37N/A return null;
37N/A if (nanos < delay || leader != null)
37N/A nanos = available.awaitNanos(nanos);
37N/A else {
37N/A Thread thisThread = Thread.currentThread();
37N/A leader = thisThread;
37N/A try {
37N/A long timeLeft = available.awaitNanos(delay);
37N/A nanos -= delay - timeLeft;
37N/A } finally {
37N/A if (leader == thisThread)
37N/A leader = null;
37N/A }
0N/A }
0N/A }
0N/A }
0N/A } finally {
37N/A if (leader == null && q.peek() != null)
37N/A available.signal();
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Retrieves, but does not remove, the head of this queue, or
0N/A * returns <tt>null</tt> if this queue is empty. Unlike
0N/A * <tt>poll</tt>, if no expired elements are available in the queue,
0N/A * this method returns the element that will expire next,
0N/A * if one exists.
0N/A *
0N/A * @return the head of this queue, or <tt>null</tt> if this
0N/A * queue is empty.
0N/A */
0N/A public E peek() {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return q.peek();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A public int size() {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return q.size();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @throws UnsupportedOperationException {@inheritDoc}
0N/A * @throws ClassCastException {@inheritDoc}
0N/A * @throws NullPointerException {@inheritDoc}
0N/A * @throws IllegalArgumentException {@inheritDoc}
0N/A */
0N/A public int drainTo(Collection<? super E> c) {
0N/A if (c == null)
0N/A throw new NullPointerException();
0N/A if (c == this)
0N/A throw new IllegalArgumentException();
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A int n = 0;
0N/A for (;;) {
0N/A E first = q.peek();
0N/A if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
0N/A break;
0N/A c.add(q.poll());
0N/A ++n;
0N/A }
0N/A return n;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * @throws UnsupportedOperationException {@inheritDoc}
0N/A * @throws ClassCastException {@inheritDoc}
0N/A * @throws NullPointerException {@inheritDoc}
0N/A * @throws IllegalArgumentException {@inheritDoc}
0N/A */
0N/A public int drainTo(Collection<? super E> c, int maxElements) {
0N/A if (c == null)
0N/A throw new NullPointerException();
0N/A if (c == this)
0N/A throw new IllegalArgumentException();
0N/A if (maxElements <= 0)
0N/A return 0;
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A int n = 0;
0N/A while (n < maxElements) {
0N/A E first = q.peek();
0N/A if (first == null || first.getDelay(TimeUnit.NANOSECONDS) > 0)
0N/A break;
0N/A c.add(q.poll());
0N/A ++n;
0N/A }
0N/A return n;
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Atomically removes all of the elements from this delay queue.
0N/A * The queue will be empty after this call returns.
0N/A * Elements with an unexpired delay are not waited for; they are
0N/A * simply discarded from the queue.
0N/A */
0N/A public void clear() {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A q.clear();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Always returns <tt>Integer.MAX_VALUE</tt> because
0N/A * a <tt>DelayQueue</tt> is not capacity constrained.
0N/A *
0N/A * @return <tt>Integer.MAX_VALUE</tt>
0N/A */
0N/A public int remainingCapacity() {
0N/A return Integer.MAX_VALUE;
0N/A }
0N/A
0N/A /**
0N/A * Returns an array containing all of the elements in this queue.
0N/A * The returned array elements are in no particular order.
0N/A *
0N/A * <p>The returned array will be "safe" in that no references to it are
0N/A * maintained by this queue. (In other words, this method must allocate
0N/A * a new array). The caller is thus free to modify the returned array.
0N/A *
0N/A * <p>This method acts as bridge between array-based and collection-based
0N/A * APIs.
0N/A *
0N/A * @return an array containing all of the elements in this queue
0N/A */
0N/A public Object[] toArray() {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return q.toArray();
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an array containing all of the elements in this queue; the
0N/A * runtime type of the returned array is that of the specified array.
0N/A * The returned array elements are in no particular order.
0N/A * If the queue fits in the specified array, it is returned therein.
0N/A * Otherwise, a new array is allocated with the runtime type of the
0N/A * specified array and the size of this queue.
0N/A *
0N/A * <p>If this queue fits in the specified array with room to spare
0N/A * (i.e., the array has more elements than this queue), the element in
0N/A * the array immediately following the end of the queue is set to
0N/A * <tt>null</tt>.
0N/A *
0N/A * <p>Like the {@link #toArray()} method, this method acts as bridge between
0N/A * array-based and collection-based APIs. Further, this method allows
0N/A * precise control over the runtime type of the output array, and may,
0N/A * under certain circumstances, be used to save allocation costs.
0N/A *
0N/A * <p>The following code can be used to dump a delay queue into a newly
0N/A * allocated array of <tt>Delayed</tt>:
0N/A *
0N/A * <pre>
0N/A * Delayed[] a = q.toArray(new Delayed[0]);</pre>
0N/A *
0N/A * Note that <tt>toArray(new Object[0])</tt> is identical in function to
0N/A * <tt>toArray()</tt>.
0N/A *
0N/A * @param a the array into which the elements of the queue are to
0N/A * be stored, if it is big enough; otherwise, a new array of the
0N/A * same runtime type is allocated for this purpose
0N/A * @return an array containing all of the elements in this queue
0N/A * @throws ArrayStoreException if the runtime type of the specified array
0N/A * is not a supertype of the runtime type of every element in
0N/A * this queue
0N/A * @throws NullPointerException if the specified array is null
0N/A */
0N/A public <T> T[] toArray(T[] a) {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return q.toArray(a);
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Removes a single instance of the specified element from this
0N/A * queue, if it is present, whether or not it has expired.
0N/A */
0N/A public boolean remove(Object o) {
0N/A final ReentrantLock lock = this.lock;
0N/A lock.lock();
0N/A try {
0N/A return q.remove(o);
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns an iterator over all the elements (both expired and
0N/A * unexpired) in this queue. The iterator does not return the
3203N/A * elements in any particular order.
3203N/A *
3203N/A * <p>The returned iterator is a "weakly consistent" iterator that
3203N/A * will never throw {@link java.util.ConcurrentModificationException
3203N/A * ConcurrentModificationException}, and guarantees to traverse
3203N/A * elements as they existed upon construction of the iterator, and
3203N/A * may (but is not guaranteed to) reflect any modifications
3203N/A * subsequent to construction.
0N/A *
0N/A * @return an iterator over the elements in this queue
0N/A */
0N/A public Iterator<E> iterator() {
0N/A return new Itr(toArray());
0N/A }
0N/A
0N/A /**
0N/A * Snapshot iterator that works off copy of underlying q array.
0N/A */
0N/A private class Itr implements Iterator<E> {
0N/A final Object[] array; // Array of all elements
0N/A int cursor; // index of next element to return;
0N/A int lastRet; // index of last element, or -1 if no such
0N/A
0N/A Itr(Object[] array) {
0N/A lastRet = -1;
0N/A this.array = array;
0N/A }
0N/A
0N/A public boolean hasNext() {
0N/A return cursor < array.length;
0N/A }
0N/A
37N/A @SuppressWarnings("unchecked")
0N/A public E next() {
0N/A if (cursor >= array.length)
0N/A throw new NoSuchElementException();
0N/A lastRet = cursor;
0N/A return (E)array[cursor++];
0N/A }
0N/A
0N/A public void remove() {
0N/A if (lastRet < 0)
0N/A throw new IllegalStateException();
0N/A Object x = array[lastRet];
0N/A lastRet = -1;
0N/A // Traverse underlying queue to find == element,
0N/A // not just a .equals element.
0N/A lock.lock();
0N/A try {
0N/A for (Iterator it = q.iterator(); it.hasNext(); ) {
0N/A if (it.next() == x) {
0N/A it.remove();
0N/A return;
0N/A }
0N/A }
0N/A } finally {
0N/A lock.unlock();
0N/A }
0N/A }
0N/A }
0N/A
0N/A}