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