001/*
002 * Copyright (C) 2011 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 */
014
015package com.google.common.collect;
016
017import com.google.common.annotations.Beta;
018import com.google.common.base.Preconditions;
019
020import java.util.ArrayDeque;
021import java.util.Collection;
022import java.util.Deque;
023import java.util.PriorityQueue;
024import java.util.Queue;
025import java.util.concurrent.ArrayBlockingQueue;
026import java.util.concurrent.BlockingQueue;
027import java.util.concurrent.ConcurrentLinkedQueue;
028import java.util.concurrent.LinkedBlockingDeque;
029import java.util.concurrent.LinkedBlockingQueue;
030import java.util.concurrent.PriorityBlockingQueue;
031import java.util.concurrent.SynchronousQueue;
032import java.util.concurrent.TimeUnit;
033
034/**
035 * Static utility methods pertaining to {@link Queue} and {@link Deque} instances.
036 * Also see this class's counterparts {@link Lists}, {@link Sets}, and {@link Maps}.
037 *
038 * @author Kurt Alfred Kluever
039 * @since 11.0
040 */
041public final class Queues {
042  private Queues() {}
043
044  // ArrayBlockingQueue
045
046  /**
047   * Creates an empty {@code ArrayBlockingQueue} instance.
048   *
049   * @return a new, empty {@code ArrayBlockingQueue}
050   */
051  public static <E> ArrayBlockingQueue<E> newArrayBlockingQueue(int capacity) {
052    return new ArrayBlockingQueue<E>(capacity);
053  }
054
055  // ArrayDeque
056
057  /**
058   * Creates an empty {@code ArrayDeque} instance.
059   *
060   * @return a new, empty {@code ArrayDeque}
061   * @since 12.0
062   */
063  public static <E> ArrayDeque<E> newArrayDeque() {
064    return new ArrayDeque<E>();
065  }
066
067  /**
068   * Creates an {@code ArrayDeque} instance containing the given elements.
069   *
070   * @param elements the elements that the queue should contain, in order
071   * @return a new {@code ArrayDeque} containing those elements
072   * @since 12.0
073   */
074  public static <E> ArrayDeque<E> newArrayDeque(Iterable<? extends E> elements) {
075    if (elements instanceof Collection) {
076      return new ArrayDeque<E>(Collections2.cast(elements));
077    }
078    ArrayDeque<E> deque = new ArrayDeque<E>();
079    Iterables.addAll(deque, elements);
080    return deque;
081  }
082
083  // ConcurrentLinkedQueue
084
085  /**
086   * Creates an empty {@code ConcurrentLinkedQueue} instance.
087   *
088   * @return a new, empty {@code ConcurrentLinkedQueue}
089   */
090  public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue() {
091    return new ConcurrentLinkedQueue<E>();
092  }
093
094  /**
095   * Creates an {@code ConcurrentLinkedQueue} instance containing the given elements.
096   *
097   * @param elements the elements that the queue should contain, in order
098   * @return a new {@code ConcurrentLinkedQueue} containing those elements
099   */
100  public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue(
101      Iterable<? extends E> elements) {
102    if (elements instanceof Collection) {
103      return new ConcurrentLinkedQueue<E>(Collections2.cast(elements));
104    }
105    ConcurrentLinkedQueue<E> queue = new ConcurrentLinkedQueue<E>();
106    Iterables.addAll(queue, elements);
107    return queue;
108  }
109
110  // LinkedBlockingDeque
111
112  /**
113   * Creates an empty {@code LinkedBlockingDeque} instance.
114   *
115   * @return a new, empty {@code LinkedBlockingDeque}
116   * @since 12.0
117   */
118  public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque() {
119    return new LinkedBlockingDeque<E>();
120  }
121
122  /**
123   * Creates a {@code LinkedBlockingDeque} with the given (fixed) capacity.
124   *
125   * @param capacity the capacity of this deque
126   * @return a new, empty {@code LinkedBlockingDeque}
127   * @throws IllegalArgumentException if {@code capacity} is less than 1
128   * @since 12.0
129   */
130  public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(int capacity) {
131    return new LinkedBlockingDeque<E>(capacity);
132  }
133
134  /**
135   * Creates an {@code LinkedBlockingDeque} instance containing the given elements.
136   *
137   * @param elements the elements that the queue should contain, in order
138   * @return a new {@code LinkedBlockingDeque} containing those elements
139   * @since 12.0
140   */
141  public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(Iterable<? extends E> elements) {
142    if (elements instanceof Collection) {
143      return new LinkedBlockingDeque<E>(Collections2.cast(elements));
144    }
145    LinkedBlockingDeque<E> deque = new LinkedBlockingDeque<E>();
146    Iterables.addAll(deque, elements);
147    return deque;
148  }
149
150  // LinkedBlockingQueue
151
152  /**
153   * Creates an empty {@code LinkedBlockingQueue} instance.
154   *
155   * @return a new, empty {@code LinkedBlockingQueue}
156   */
157  public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue() {
158    return new LinkedBlockingQueue<E>();
159  }
160
161  /**
162   * Creates a {@code LinkedBlockingQueue} with the given (fixed) capacity.
163   *
164   * @param capacity the capacity of this queue
165   * @return a new, empty {@code LinkedBlockingQueue}
166   * @throws IllegalArgumentException if {@code capacity} is less than 1
167   */
168  public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(int capacity) {
169    return new LinkedBlockingQueue<E>(capacity);
170  }
171
172  /**
173   * Creates an {@code LinkedBlockingQueue} instance containing the given elements.
174   *
175   * @param elements the elements that the queue should contain, in order
176   * @return a new {@code LinkedBlockingQueue} containing those elements
177   */
178  public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(Iterable<? extends E> elements) {
179    if (elements instanceof Collection) {
180      return new LinkedBlockingQueue<E>(Collections2.cast(elements));
181    }
182    LinkedBlockingQueue<E> queue = new LinkedBlockingQueue<E>();
183    Iterables.addAll(queue, elements);
184    return queue;
185  }
186
187  // LinkedList: see {@link com.google.common.collect.Lists}
188
189  // PriorityBlockingQueue
190
191  /**
192   * Creates an empty {@code PriorityBlockingQueue} instance.
193   *
194   * @return a new, empty {@code PriorityBlockingQueue}
195   */
196  public static <E> PriorityBlockingQueue<E> newPriorityBlockingQueue() {
197    return new PriorityBlockingQueue<E>();
198  }
199
200  /**
201   * Creates an {@code PriorityBlockingQueue} instance containing the given elements.
202   *
203   * @param elements the elements that the queue should contain, in order
204   * @return a new {@code PriorityBlockingQueue} containing those elements
205   */
206  public static <E> PriorityBlockingQueue<E> newPriorityBlockingQueue(
207      Iterable<? extends E> elements) {
208    if (elements instanceof Collection) {
209      return new PriorityBlockingQueue<E>(Collections2.cast(elements));
210    }
211    PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<E>();
212    Iterables.addAll(queue, elements);
213    return queue;
214  }
215
216  // PriorityQueue
217
218  /**
219   * Creates an empty {@code PriorityQueue} instance.
220   *
221   * @return a new, empty {@code PriorityQueue}
222   */
223  public static <E> PriorityQueue<E> newPriorityQueue() {
224    return new PriorityQueue<E>();
225  }
226
227  /**
228   * Creates an {@code PriorityQueue} instance containing the given elements.
229   *
230   * @param elements the elements that the queue should contain, in order
231   * @return a new {@code PriorityQueue} containing those elements
232   */
233  public static <E> PriorityQueue<E> newPriorityQueue(Iterable<? extends E> elements) {
234    if (elements instanceof Collection) {
235      return new PriorityQueue<E>(Collections2.cast(elements));
236    }
237    PriorityQueue<E> queue = new PriorityQueue<E>();
238    Iterables.addAll(queue, elements);
239    return queue;
240  }
241
242  // SynchronousQueue
243
244  /**
245   * Creates an empty {@code SynchronousQueue} instance.
246   *
247   * @return a new, empty {@code SynchronousQueue}
248   */
249  public static <E> SynchronousQueue<E> newSynchronousQueue() {
250    return new SynchronousQueue<E>();
251  }
252  
253  /**
254   * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested 
255   * {@code numElements} elements are not available, it will wait for them up to the specified
256   * timeout.
257   * 
258   * @param q the blocking queue to be drained
259   * @param buffer where to add the transferred elements
260   * @param numElements the number of elements to be waited for
261   * @param timeout how long to wait before giving up, in units of {@code unit}
262   * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
263   * @return the number of elements transferred
264   * @throws InterruptedException if interrupted while waiting
265   */
266  @Beta
267  public static <E> int drain(BlockingQueue<E> q, Collection<? super E> buffer, int numElements,
268      long timeout, TimeUnit unit) throws InterruptedException {
269    Preconditions.checkNotNull(buffer);
270    /*
271     * This code performs one System.nanoTime() more than necessary, and in return, the time to
272     * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make
273     * the timeout arbitrarily inaccurate, given a queue that is slow to drain).
274     */
275    long deadline = System.nanoTime() + unit.toNanos(timeout);
276    int added = 0;
277    while (added < numElements) {
278      // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple
279      // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
280      added += q.drainTo(buffer, numElements - added);
281      if (added < numElements) { // not enough elements immediately available; will have to poll
282        E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
283        if (e == null) {
284          break; // we already waited enough, and there are no more elements in sight
285        }
286        buffer.add(e);
287        added++;
288      }
289    }
290    return added;
291  }
292  
293  /**
294   * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)}, 
295   * but with a different behavior in case it is interrupted while waiting. In that case, the 
296   * operation will continue as usual, and in the end the thread's interruption status will be set 
297   * (no {@code InterruptedException} is thrown). 
298   * 
299   * @param q the blocking queue to be drained
300   * @param buffer where to add the transferred elements
301   * @param numElements the number of elements to be waited for
302   * @param timeout how long to wait before giving up, in units of {@code unit}
303   * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
304   * @return the number of elements transferred
305   */
306  @Beta
307  public static <E> int drainUninterruptibly(BlockingQueue<E> q, Collection<? super E> buffer, 
308      int numElements, long timeout, TimeUnit unit) {
309    Preconditions.checkNotNull(buffer);
310    long deadline = System.nanoTime() + unit.toNanos(timeout);
311    int added = 0;
312    boolean interrupted = false;
313    try {
314      while (added < numElements) {
315        // we could rely solely on #poll, but #drainTo might be more efficient when there are 
316        // multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
317        added += q.drainTo(buffer, numElements - added);
318        if (added < numElements) { // not enough elements immediately available; will have to poll
319          E e; // written exactly once, by a successful (uninterrupted) invocation of #poll
320          while (true) {
321            try {
322              e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
323              break;
324            } catch (InterruptedException ex) {
325              interrupted = true; // note interruption and retry
326            }
327          }
328          if (e == null) {
329            break; // we already waited enough, and there are no more elements in sight
330          }
331          buffer.add(e);
332          added++;
333        }
334      }
335    } finally {
336      if (interrupted) {
337        Thread.currentThread().interrupt();
338      }
339    }
340    return added;
341  }
342
343  /**
344   * Returns a synchronized (thread-safe) queue backed by the specified queue. In order to
345   * guarantee serial access, it is critical that <b>all</b> access to the backing queue is
346   * accomplished through the returned queue.
347   *
348   * <p>It is imperative that the user manually synchronize on the returned queue when accessing
349   * the queue's iterator: <pre>   {@code
350   *
351   *   Queue<E> queue = Queues.synchronizedQueue(MinMaxPriorityQueue<E>.create());
352   *   ...
353   *   queue.add(element);  // Needn't be in synchronized block
354   *   ...
355   *   synchronized (queue) {  // Must synchronize on queue!
356   *     Iterator<E> i = queue.iterator(); // Must be in synchronized block
357   *     while (i.hasNext()) {
358   *       foo(i.next());
359   *     }
360   *   }}</pre>
361   *
362   * Failure to follow this advice may result in non-deterministic behavior.
363   *
364   * <p>The returned queue will be serializable if the specified queue is serializable.
365   *
366   * @param queue the queue to be wrapped in a synchronized view
367   * @return a synchronized view of the specified queue
368   * @since 14.0
369   */
370  @Beta
371  public static <E> Queue<E> synchronizedQueue(Queue<E> queue) {
372    return Synchronized.queue(queue, null);
373  }
374}