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