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 static java.util.concurrent.TimeUnit.NANOSECONDS;
018
019import com.google.common.annotations.GwtCompatible;
020import com.google.common.annotations.GwtIncompatible;
021import com.google.common.annotations.J2ktIncompatible;
022import com.google.common.base.Preconditions;
023import com.google.errorprone.annotations.CanIgnoreReturnValue;
024import java.time.Duration;
025import java.util.ArrayDeque;
026import java.util.Collection;
027import java.util.Deque;
028import java.util.PriorityQueue;
029import java.util.Queue;
030import java.util.concurrent.ArrayBlockingQueue;
031import java.util.concurrent.BlockingQueue;
032import java.util.concurrent.ConcurrentLinkedQueue;
033import java.util.concurrent.LinkedBlockingDeque;
034import java.util.concurrent.LinkedBlockingQueue;
035import java.util.concurrent.PriorityBlockingQueue;
036import java.util.concurrent.SynchronousQueue;
037import java.util.concurrent.TimeUnit;
038import org.checkerframework.checker.nullness.qual.Nullable;
039
040/**
041 * Static utility methods pertaining to {@link Queue} and {@link Deque} instances. Also see this
042 * class's counterparts {@link Lists}, {@link Sets}, and {@link Maps}.
043 *
044 * @author Kurt Alfred Kluever
045 * @since 11.0
046 */
047@GwtCompatible(emulated = true)
048@ElementTypesAreNonnullByDefault
049public final class Queues {
050  private Queues() {}
051
052  // ArrayBlockingQueue
053
054  /**
055   * Creates an empty {@code ArrayBlockingQueue} with the given (fixed) capacity and nonfair access
056   * policy.
057   */
058  @J2ktIncompatible
059  @GwtIncompatible // ArrayBlockingQueue
060  public static <E> ArrayBlockingQueue<E> newArrayBlockingQueue(int capacity) {
061    return new ArrayBlockingQueue<>(capacity);
062  }
063
064  // ArrayDeque
065
066  /**
067   * Creates an empty {@code ArrayDeque}.
068   *
069   * @since 12.0
070   */
071  public static <E> ArrayDeque<E> newArrayDeque() {
072    return new ArrayDeque<>();
073  }
074
075  /**
076   * Creates an {@code ArrayDeque} containing the elements of the specified iterable, in the order
077   * they are returned by the iterable's iterator.
078   *
079   * @since 12.0
080   */
081  public static <E> ArrayDeque<E> newArrayDeque(Iterable<? extends E> elements) {
082    if (elements instanceof Collection) {
083      return new ArrayDeque<>((Collection<? extends E>) elements);
084    }
085    ArrayDeque<E> deque = new ArrayDeque<>();
086    Iterables.addAll(deque, elements);
087    return deque;
088  }
089
090  // ConcurrentLinkedQueue
091
092  /** Creates an empty {@code ConcurrentLinkedQueue}. */
093  @J2ktIncompatible
094  @GwtIncompatible // ConcurrentLinkedQueue
095  public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue() {
096    return new ConcurrentLinkedQueue<>();
097  }
098
099  /**
100   * Creates a {@code ConcurrentLinkedQueue} containing the elements of the specified iterable, in
101   * the order they are returned by the iterable's iterator.
102   */
103  @J2ktIncompatible
104  @GwtIncompatible // ConcurrentLinkedQueue
105  public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue(
106      Iterable<? extends E> elements) {
107    if (elements instanceof Collection) {
108      return new ConcurrentLinkedQueue<>((Collection<? extends E>) elements);
109    }
110    ConcurrentLinkedQueue<E> queue = new ConcurrentLinkedQueue<>();
111    Iterables.addAll(queue, elements);
112    return queue;
113  }
114
115  // LinkedBlockingDeque
116
117  /**
118   * Creates an empty {@code LinkedBlockingDeque} with a capacity of {@link Integer#MAX_VALUE}.
119   *
120   * @since 12.0
121   */
122  @J2ktIncompatible
123  @GwtIncompatible // LinkedBlockingDeque
124  public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque() {
125    return new LinkedBlockingDeque<>();
126  }
127
128  /**
129   * Creates an empty {@code LinkedBlockingDeque} with the given (fixed) capacity.
130   *
131   * @throws IllegalArgumentException if {@code capacity} is less than 1
132   * @since 12.0
133   */
134  @J2ktIncompatible
135  @GwtIncompatible // LinkedBlockingDeque
136  public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(int capacity) {
137    return new LinkedBlockingDeque<>(capacity);
138  }
139
140  /**
141   * Creates a {@code LinkedBlockingDeque} with a capacity of {@link Integer#MAX_VALUE}, containing
142   * the elements of the specified iterable, in the order they are returned by the iterable's
143   * iterator.
144   *
145   * @since 12.0
146   */
147  @J2ktIncompatible
148  @GwtIncompatible // LinkedBlockingDeque
149  public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(Iterable<? extends E> elements) {
150    if (elements instanceof Collection) {
151      return new LinkedBlockingDeque<>((Collection<? extends E>) elements);
152    }
153    LinkedBlockingDeque<E> deque = new LinkedBlockingDeque<>();
154    Iterables.addAll(deque, elements);
155    return deque;
156  }
157
158  // LinkedBlockingQueue
159
160  /** Creates an empty {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}. */
161  @J2ktIncompatible
162  @GwtIncompatible // LinkedBlockingQueue
163  public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue() {
164    return new LinkedBlockingQueue<>();
165  }
166
167  /**
168   * Creates an empty {@code LinkedBlockingQueue} with the given (fixed) capacity.
169   *
170   * @throws IllegalArgumentException if {@code capacity} is less than 1
171   */
172  @J2ktIncompatible
173  @GwtIncompatible // LinkedBlockingQueue
174  public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(int capacity) {
175    return new LinkedBlockingQueue<>(capacity);
176  }
177
178  /**
179   * Creates a {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}, containing
180   * the elements of the specified iterable, in the order they are returned by the iterable's
181   * iterator.
182   *
183   * @param elements the elements that the queue should contain, in order
184   * @return a new {@code LinkedBlockingQueue} containing those elements
185   */
186  @J2ktIncompatible
187  @GwtIncompatible // LinkedBlockingQueue
188  public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(Iterable<? extends E> elements) {
189    if (elements instanceof Collection) {
190      return new LinkedBlockingQueue<>((Collection<? extends E>) elements);
191    }
192    LinkedBlockingQueue<E> queue = new LinkedBlockingQueue<>();
193    Iterables.addAll(queue, elements);
194    return queue;
195  }
196
197  // LinkedList: see {@link com.google.common.collect.Lists}
198
199  // PriorityBlockingQueue
200
201  /**
202   * Creates an empty {@code PriorityBlockingQueue} with the ordering given by its elements' natural
203   * ordering.
204   *
205   * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable}
206   *     in 15.0)
207   */
208  @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
209  @J2ktIncompatible
210  @GwtIncompatible // PriorityBlockingQueue
211  public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue() {
212    return new PriorityBlockingQueue<>();
213  }
214
215  /**
216   * Creates a {@code PriorityBlockingQueue} containing the given elements.
217   *
218   * <p><b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue},
219   * this priority queue will be ordered according to the same ordering.
220   *
221   * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable}
222   *     in 15.0)
223   */
224  @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
225  @J2ktIncompatible
226  @GwtIncompatible // PriorityBlockingQueue
227  public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue(
228      Iterable<? extends E> elements) {
229    if (elements instanceof Collection) {
230      return new PriorityBlockingQueue<>((Collection<? extends E>) elements);
231    }
232    PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<>();
233    Iterables.addAll(queue, elements);
234    return queue;
235  }
236
237  // PriorityQueue
238
239  /**
240   * Creates an empty {@code PriorityQueue} with the ordering given by its elements' natural
241   * ordering.
242   *
243   * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable}
244   *     in 15.0)
245   */
246  @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
247  public static <E extends Comparable> PriorityQueue<E> newPriorityQueue() {
248    return new PriorityQueue<>();
249  }
250
251  /**
252   * Creates a {@code PriorityQueue} containing the given elements.
253   *
254   * <p><b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue},
255   * this priority queue will be ordered according to the same ordering.
256   *
257   * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable}
258   *     in 15.0)
259   */
260  @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
261  public static <E extends Comparable> PriorityQueue<E> newPriorityQueue(
262      Iterable<? extends E> elements) {
263    if (elements instanceof Collection) {
264      return new PriorityQueue<>((Collection<? extends E>) elements);
265    }
266    PriorityQueue<E> queue = new PriorityQueue<>();
267    Iterables.addAll(queue, elements);
268    return queue;
269  }
270
271  // SynchronousQueue
272
273  /** Creates an empty {@code SynchronousQueue} with nonfair access policy. */
274  @J2ktIncompatible
275  @GwtIncompatible // SynchronousQueue
276  public static <E> SynchronousQueue<E> newSynchronousQueue() {
277    return new SynchronousQueue<>();
278  }
279
280  /**
281   * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested {@code
282   * numElements} elements are not available, it will wait for them up to the specified timeout.
283   *
284   * @param q the blocking queue to be drained
285   * @param buffer where to add the transferred elements
286   * @param numElements the number of elements to be waited for
287   * @param timeout how long to wait before giving up
288   * @return the number of elements transferred
289   * @throws InterruptedException if interrupted while waiting
290   * @since 28.0 (but only since 33.4.0 in the Android flavor)
291   */
292  @CanIgnoreReturnValue
293  @J2ktIncompatible
294  @GwtIncompatible // BlockingQueue
295  public static <E> int drain(
296      BlockingQueue<E> q, Collection<? super E> buffer, int numElements, Duration timeout)
297      throws InterruptedException {
298    // TODO(b/126049426): Consider using saturateToNanos(timeout) instead.
299    return drain(q, buffer, numElements, timeout.toNanos(), NANOSECONDS);
300  }
301
302  /**
303   * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested {@code
304   * numElements} elements are not available, it will wait for them up to the specified timeout.
305   *
306   * @param q the blocking queue to be drained
307   * @param buffer where to add the transferred elements
308   * @param numElements the number of elements to be waited for
309   * @param timeout how long to wait before giving up, in units of {@code unit}
310   * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
311   * @return the number of elements transferred
312   * @throws InterruptedException if interrupted while waiting
313   */
314  @CanIgnoreReturnValue
315  @J2ktIncompatible
316  @GwtIncompatible // BlockingQueue
317  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
318  public static <E> int drain(
319      BlockingQueue<E> q,
320      Collection<? super E> buffer,
321      int numElements,
322      long timeout,
323      TimeUnit unit)
324      throws InterruptedException {
325    Preconditions.checkNotNull(buffer);
326    /*
327     * This code performs one System.nanoTime() more than necessary, and in return, the time to
328     * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make
329     * the timeout arbitrarily inaccurate, given a queue that is slow to drain).
330     */
331    long deadline = System.nanoTime() + unit.toNanos(timeout);
332    int added = 0;
333    while (added < numElements) {
334      // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple
335      // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
336      added += q.drainTo(buffer, numElements - added);
337      if (added < numElements) { // not enough elements immediately available; will have to poll
338        E e = q.poll(deadline - System.nanoTime(), NANOSECONDS);
339        if (e == null) {
340          break; // we already waited enough, and there are no more elements in sight
341        }
342        buffer.add(e);
343        added++;
344      }
345    }
346    return added;
347  }
348
349  /**
350   * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, Duration)}, but with a
351   * different behavior in case it is interrupted while waiting. In that case, the operation will
352   * continue as usual, and in the end the thread's interruption status will be set (no {@code
353   * InterruptedException} is thrown).
354   *
355   * @param q the blocking queue to be drained
356   * @param buffer where to add the transferred elements
357   * @param numElements the number of elements to be waited for
358   * @param timeout how long to wait before giving up
359   * @return the number of elements transferred
360   * @since 28.0 (but only since 33.4.0 in the Android flavor)
361   */
362  @CanIgnoreReturnValue
363  @J2ktIncompatible
364  @GwtIncompatible // BlockingQueue
365  public static <E> int drainUninterruptibly(
366      BlockingQueue<E> q, Collection<? super E> buffer, int numElements, Duration timeout) {
367    // TODO(b/126049426): Consider using saturateToNanos(timeout) instead.
368    return drainUninterruptibly(q, buffer, numElements, timeout.toNanos(), NANOSECONDS);
369  }
370
371  /**
372   * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)}, but
373   * with a different behavior in case it is interrupted while waiting. In that case, the operation
374   * will continue as usual, and in the end the thread's interruption status will be set (no {@code
375   * InterruptedException} is thrown).
376   *
377   * @param q the blocking queue to be drained
378   * @param buffer where to add the transferred elements
379   * @param numElements the number of elements to be waited for
380   * @param timeout how long to wait before giving up, in units of {@code unit}
381   * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
382   * @return the number of elements transferred
383   */
384  @CanIgnoreReturnValue
385  @J2ktIncompatible
386  @GwtIncompatible // BlockingQueue
387  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
388  public static <E> int drainUninterruptibly(
389      BlockingQueue<E> q,
390      Collection<? super E> buffer,
391      int numElements,
392      long timeout,
393      TimeUnit unit) {
394    Preconditions.checkNotNull(buffer);
395    long deadline = System.nanoTime() + unit.toNanos(timeout);
396    int added = 0;
397    boolean interrupted = false;
398    try {
399      while (added < numElements) {
400        // we could rely solely on #poll, but #drainTo might be more efficient when there are
401        // multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
402        added += q.drainTo(buffer, numElements - added);
403        if (added < numElements) { // not enough elements immediately available; will have to poll
404          E e; // written exactly once, by a successful (uninterrupted) invocation of #poll
405          while (true) {
406            try {
407              e = q.poll(deadline - System.nanoTime(), NANOSECONDS);
408              break;
409            } catch (InterruptedException ex) {
410              interrupted = true; // note interruption and retry
411            }
412          }
413          if (e == null) {
414            break; // we already waited enough, and there are no more elements in sight
415          }
416          buffer.add(e);
417          added++;
418        }
419      }
420    } finally {
421      if (interrupted) {
422        Thread.currentThread().interrupt();
423      }
424    }
425    return added;
426  }
427
428  /**
429   * Returns a synchronized (thread-safe) queue backed by the specified queue. In order to guarantee
430   * serial access, it is critical that <b>all</b> access to the backing queue is accomplished
431   * through the returned queue.
432   *
433   * <p>It is imperative that the user manually synchronize on the returned queue when accessing the
434   * queue's iterator:
435   *
436   * <pre>{@code
437   * Queue<E> queue = Queues.synchronizedQueue(MinMaxPriorityQueue.<E>create());
438   * ...
439   * queue.add(element);  // Needn't be in synchronized block
440   * ...
441   * synchronized (queue) {  // Must synchronize on queue!
442   *   Iterator<E> i = queue.iterator(); // Must be in synchronized block
443   *   while (i.hasNext()) {
444   *     foo(i.next());
445   *   }
446   * }
447   * }</pre>
448   *
449   * <p>Failure to follow this advice may result in non-deterministic behavior.
450   *
451   * <p>The returned queue will be serializable if the specified queue is serializable.
452   *
453   * @param queue the queue to be wrapped in a synchronized view
454   * @return a synchronized view of the specified queue
455   * @since 14.0
456   */
457  @J2ktIncompatible // Synchronized
458  public static <E extends @Nullable Object> Queue<E> synchronizedQueue(Queue<E> queue) {
459    return Synchronized.queue(queue, null);
460  }
461
462  /**
463   * Returns a synchronized (thread-safe) deque backed by the specified deque. In order to guarantee
464   * serial access, it is critical that <b>all</b> access to the backing deque is accomplished
465   * through the returned deque.
466   *
467   * <p>It is imperative that the user manually synchronize on the returned deque when accessing any
468   * of the deque's iterators:
469   *
470   * <pre>{@code
471   * Deque<E> deque = Queues.synchronizedDeque(Queues.<E>newArrayDeque());
472   * ...
473   * deque.add(element);  // Needn't be in synchronized block
474   * ...
475   * synchronized (deque) {  // Must synchronize on deque!
476   *   Iterator<E> i = deque.iterator(); // Must be in synchronized block
477   *   while (i.hasNext()) {
478   *     foo(i.next());
479   *   }
480   * }
481   * }</pre>
482   *
483   * <p>Failure to follow this advice may result in non-deterministic behavior.
484   *
485   * <p>The returned deque will be serializable if the specified deque is serializable.
486   *
487   * @param deque the deque to be wrapped in a synchronized view
488   * @return a synchronized view of the specified deque
489   * @since 15.0
490   */
491  @J2ktIncompatible // Synchronized
492  public static <E extends @Nullable Object> Deque<E> synchronizedDeque(Deque<E> deque) {
493    return Synchronized.deque(deque, null);
494  }
495}