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<>(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<>();
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<>((Collection<? extends E>) elements);
081    }
082    ArrayDeque<E> deque = new ArrayDeque<>();
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<>();
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<>((Collection<? extends E>) elements);
106    }
107    ConcurrentLinkedQueue<E> queue = new ConcurrentLinkedQueue<>();
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<>();
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<>(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<>((Collection<? extends E>) elements);
149    }
150    LinkedBlockingDeque<E> deque = new LinkedBlockingDeque<>();
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<>();
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<>(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<>((Collection<? extends E>) elements);
188    }
189    LinkedBlockingQueue<E> queue = new LinkedBlockingQueue<>();
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  @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
206  @J2ktIncompatible
207  @GwtIncompatible // PriorityBlockingQueue
208  public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue() {
209    return new PriorityBlockingQueue<>();
210  }
211
212  /**
213   * Creates a {@code PriorityBlockingQueue} containing the given elements.
214   *
215   * <p><b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue},
216   * this priority queue will be ordered according to the same ordering.
217   *
218   * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable}
219   *     in 15.0)
220   */
221  @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
222  @J2ktIncompatible
223  @GwtIncompatible // PriorityBlockingQueue
224  public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue(
225      Iterable<? extends E> elements) {
226    if (elements instanceof Collection) {
227      return new PriorityBlockingQueue<>((Collection<? extends E>) elements);
228    }
229    PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<>();
230    Iterables.addAll(queue, elements);
231    return queue;
232  }
233
234  // PriorityQueue
235
236  /**
237   * Creates an empty {@code PriorityQueue} with the ordering given by its elements' natural
238   * ordering.
239   *
240   * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable}
241   *     in 15.0)
242   */
243  @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
244  public static <E extends Comparable> PriorityQueue<E> newPriorityQueue() {
245    return new PriorityQueue<>();
246  }
247
248  /**
249   * Creates a {@code PriorityQueue} containing the given elements.
250   *
251   * <p><b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue},
252   * this priority queue will be ordered according to the same ordering.
253   *
254   * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable}
255   *     in 15.0)
256   */
257  @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989
258  public static <E extends Comparable> PriorityQueue<E> newPriorityQueue(
259      Iterable<? extends E> elements) {
260    if (elements instanceof Collection) {
261      return new PriorityQueue<>((Collection<? extends E>) elements);
262    }
263    PriorityQueue<E> queue = new PriorityQueue<>();
264    Iterables.addAll(queue, elements);
265    return queue;
266  }
267
268  // SynchronousQueue
269
270  /** Creates an empty {@code SynchronousQueue} with nonfair access policy. */
271  @J2ktIncompatible
272  @GwtIncompatible // SynchronousQueue
273  public static <E> SynchronousQueue<E> newSynchronousQueue() {
274    return new SynchronousQueue<>();
275  }
276
277  /**
278   * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested {@code
279   * numElements} elements are not available, it will wait for them up to the specified timeout.
280   *
281   * @param q the blocking queue to be drained
282   * @param buffer where to add the transferred elements
283   * @param numElements the number of elements to be waited for
284   * @param timeout how long to wait before giving up, in units of {@code unit}
285   * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
286   * @return the number of elements transferred
287   * @throws InterruptedException if interrupted while waiting
288   */
289  @CanIgnoreReturnValue
290  @J2ktIncompatible
291  @GwtIncompatible // BlockingQueue
292  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
293  public static <E> int drain(
294      BlockingQueue<E> q,
295      Collection<? super E> buffer,
296      int numElements,
297      long timeout,
298      TimeUnit unit)
299      throws InterruptedException {
300    Preconditions.checkNotNull(buffer);
301    /*
302     * This code performs one System.nanoTime() more than necessary, and in return, the time to
303     * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make
304     * the timeout arbitrarily inaccurate, given a queue that is slow to drain).
305     */
306    long deadline = System.nanoTime() + unit.toNanos(timeout);
307    int added = 0;
308    while (added < numElements) {
309      // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple
310      // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
311      added += q.drainTo(buffer, numElements - added);
312      if (added < numElements) { // not enough elements immediately available; will have to poll
313        E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
314        if (e == null) {
315          break; // we already waited enough, and there are no more elements in sight
316        }
317        buffer.add(e);
318        added++;
319      }
320    }
321    return added;
322  }
323
324  /**
325   * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)}, but
326   * with a different behavior in case it is interrupted while waiting. In that case, the operation
327   * will continue as usual, and in the end the thread's interruption status will be set (no {@code
328   * InterruptedException} is thrown).
329   *
330   * @param q the blocking queue to be drained
331   * @param buffer where to add the transferred elements
332   * @param numElements the number of elements to be waited for
333   * @param timeout how long to wait before giving up, in units of {@code unit}
334   * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
335   * @return the number of elements transferred
336   */
337  @CanIgnoreReturnValue
338  @J2ktIncompatible
339  @GwtIncompatible // BlockingQueue
340  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
341  public static <E> int drainUninterruptibly(
342      BlockingQueue<E> q,
343      Collection<? super E> buffer,
344      int numElements,
345      long timeout,
346      TimeUnit unit) {
347    Preconditions.checkNotNull(buffer);
348    long deadline = System.nanoTime() + unit.toNanos(timeout);
349    int added = 0;
350    boolean interrupted = false;
351    try {
352      while (added < numElements) {
353        // we could rely solely on #poll, but #drainTo might be more efficient when there are
354        // multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
355        added += q.drainTo(buffer, numElements - added);
356        if (added < numElements) { // not enough elements immediately available; will have to poll
357          E e; // written exactly once, by a successful (uninterrupted) invocation of #poll
358          while (true) {
359            try {
360              e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS);
361              break;
362            } catch (InterruptedException ex) {
363              interrupted = true; // note interruption and retry
364            }
365          }
366          if (e == null) {
367            break; // we already waited enough, and there are no more elements in sight
368          }
369          buffer.add(e);
370          added++;
371        }
372      }
373    } finally {
374      if (interrupted) {
375        Thread.currentThread().interrupt();
376      }
377    }
378    return added;
379  }
380
381  /**
382   * Returns a synchronized (thread-safe) queue backed by the specified queue. In order to guarantee
383   * serial access, it is critical that <b>all</b> access to the backing queue is accomplished
384   * through the returned queue.
385   *
386   * <p>It is imperative that the user manually synchronize on the returned queue when accessing the
387   * queue's iterator:
388   *
389   * <pre>{@code
390   * Queue<E> queue = Queues.synchronizedQueue(MinMaxPriorityQueue.<E>create());
391   * ...
392   * queue.add(element);  // Needn't be in synchronized block
393   * ...
394   * synchronized (queue) {  // Must synchronize on queue!
395   *   Iterator<E> i = queue.iterator(); // Must be in synchronized block
396   *   while (i.hasNext()) {
397   *     foo(i.next());
398   *   }
399   * }
400   * }</pre>
401   *
402   * <p>Failure to follow this advice may result in non-deterministic behavior.
403   *
404   * <p>The returned queue will be serializable if the specified queue is serializable.
405   *
406   * @param queue the queue to be wrapped in a synchronized view
407   * @return a synchronized view of the specified queue
408   * @since 14.0
409   */
410  public static <E extends @Nullable Object> Queue<E> synchronizedQueue(Queue<E> queue) {
411    return Synchronized.queue(queue, null);
412  }
413
414  /**
415   * Returns a synchronized (thread-safe) deque backed by the specified deque. In order to guarantee
416   * serial access, it is critical that <b>all</b> access to the backing deque is accomplished
417   * through the returned deque.
418   *
419   * <p>It is imperative that the user manually synchronize on the returned deque when accessing any
420   * of the deque's iterators:
421   *
422   * <pre>{@code
423   * Deque<E> deque = Queues.synchronizedDeque(Queues.<E>newArrayDeque());
424   * ...
425   * deque.add(element);  // Needn't be in synchronized block
426   * ...
427   * synchronized (deque) {  // Must synchronize on deque!
428   *   Iterator<E> i = deque.iterator(); // Must be in synchronized block
429   *   while (i.hasNext()) {
430   *     foo(i.next());
431   *   }
432   * }
433   * }</pre>
434   *
435   * <p>Failure to follow this advice may result in non-deterministic behavior.
436   *
437   * <p>The returned deque will be serializable if the specified deque is serializable.
438   *
439   * @param deque the deque to be wrapped in a synchronized view
440   * @return a synchronized view of the specified deque
441   * @since 15.0
442   */
443  public static <E extends @Nullable Object> Deque<E> synchronizedDeque(Deque<E> deque) {
444    return Synchronized.deque(deque, null);
445  }
446}