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.util.ArrayDeque;
025import java.util.Collection;
026import java.util.Deque;
027import java.util.PriorityQueue;
028import java.util.Queue;
029import java.util.concurrent.ArrayBlockingQueue;
030import java.util.concurrent.BlockingQueue;
031import java.util.concurrent.ConcurrentLinkedQueue;
032import java.util.concurrent.LinkedBlockingDeque;
033import java.util.concurrent.LinkedBlockingQueue;
034import java.util.concurrent.PriorityBlockingQueue;
035import java.util.concurrent.SynchronousQueue;
036import java.util.concurrent.TimeUnit;
037import org.checkerframework.checker.nullness.qual.Nullable;
038
039/**
040 * Static utility methods pertaining to {@link Queue} and {@link Deque} instances. Also see this
041 * class's counterparts {@link Lists}, {@link Sets}, and {@link Maps}.
042 *
043 * @author Kurt Alfred Kluever
044 * @since 11.0
045 */
046@GwtCompatible(emulated = true)
047@ElementTypesAreNonnullByDefault
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, in units of {@code unit}
287   * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
288   * @return the number of elements transferred
289   * @throws InterruptedException if interrupted while waiting
290   */
291  @CanIgnoreReturnValue
292  @J2ktIncompatible
293  @GwtIncompatible // BlockingQueue
294  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
295  public static <E> int drain(
296      BlockingQueue<E> q,
297      Collection<? super E> buffer,
298      int numElements,
299      long timeout,
300      TimeUnit unit)
301      throws InterruptedException {
302    Preconditions.checkNotNull(buffer);
303    /*
304     * This code performs one System.nanoTime() more than necessary, and in return, the time to
305     * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make
306     * the timeout arbitrarily inaccurate, given a queue that is slow to drain).
307     */
308    long deadline = System.nanoTime() + unit.toNanos(timeout);
309    int added = 0;
310    while (added < numElements) {
311      // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple
312      // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
313      added += q.drainTo(buffer, numElements - added);
314      if (added < numElements) { // not enough elements immediately available; will have to poll
315        E e = q.poll(deadline - System.nanoTime(), NANOSECONDS);
316        if (e == null) {
317          break; // we already waited enough, and there are no more elements in sight
318        }
319        buffer.add(e);
320        added++;
321      }
322    }
323    return added;
324  }
325
326  /**
327   * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)}, but
328   * with a different behavior in case it is interrupted while waiting. In that case, the operation
329   * will continue as usual, and in the end the thread's interruption status will be set (no {@code
330   * InterruptedException} is thrown).
331   *
332   * @param q the blocking queue to be drained
333   * @param buffer where to add the transferred elements
334   * @param numElements the number of elements to be waited for
335   * @param timeout how long to wait before giving up, in units of {@code unit}
336   * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter
337   * @return the number of elements transferred
338   */
339  @CanIgnoreReturnValue
340  @J2ktIncompatible
341  @GwtIncompatible // BlockingQueue
342  @SuppressWarnings("GoodTime") // should accept a java.time.Duration
343  public static <E> int drainUninterruptibly(
344      BlockingQueue<E> q,
345      Collection<? super E> buffer,
346      int numElements,
347      long timeout,
348      TimeUnit unit) {
349    Preconditions.checkNotNull(buffer);
350    long deadline = System.nanoTime() + unit.toNanos(timeout);
351    int added = 0;
352    boolean interrupted = false;
353    try {
354      while (added < numElements) {
355        // we could rely solely on #poll, but #drainTo might be more efficient when there are
356        // multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once)
357        added += q.drainTo(buffer, numElements - added);
358        if (added < numElements) { // not enough elements immediately available; will have to poll
359          E e; // written exactly once, by a successful (uninterrupted) invocation of #poll
360          while (true) {
361            try {
362              e = q.poll(deadline - System.nanoTime(), NANOSECONDS);
363              break;
364            } catch (InterruptedException ex) {
365              interrupted = true; // note interruption and retry
366            }
367          }
368          if (e == null) {
369            break; // we already waited enough, and there are no more elements in sight
370          }
371          buffer.add(e);
372          added++;
373        }
374      }
375    } finally {
376      if (interrupted) {
377        Thread.currentThread().interrupt();
378      }
379    }
380    return added;
381  }
382
383  /**
384   * Returns a synchronized (thread-safe) queue backed by the specified queue. In order to guarantee
385   * serial access, it is critical that <b>all</b> access to the backing queue is accomplished
386   * through the returned queue.
387   *
388   * <p>It is imperative that the user manually synchronize on the returned queue when accessing the
389   * queue's iterator:
390   *
391   * <pre>{@code
392   * Queue<E> queue = Queues.synchronizedQueue(MinMaxPriorityQueue.<E>create());
393   * ...
394   * queue.add(element);  // Needn't be in synchronized block
395   * ...
396   * synchronized (queue) {  // Must synchronize on queue!
397   *   Iterator<E> i = queue.iterator(); // Must be in synchronized block
398   *   while (i.hasNext()) {
399   *     foo(i.next());
400   *   }
401   * }
402   * }</pre>
403   *
404   * <p>Failure to follow this advice may result in non-deterministic behavior.
405   *
406   * <p>The returned queue will be serializable if the specified queue is serializable.
407   *
408   * @param queue the queue to be wrapped in a synchronized view
409   * @return a synchronized view of the specified queue
410   * @since 14.0
411   */
412  @J2ktIncompatible // Synchronized
413  public static <E extends @Nullable Object> Queue<E> synchronizedQueue(Queue<E> queue) {
414    return Synchronized.queue(queue, null);
415  }
416
417  /**
418   * Returns a synchronized (thread-safe) deque backed by the specified deque. In order to guarantee
419   * serial access, it is critical that <b>all</b> access to the backing deque is accomplished
420   * through the returned deque.
421   *
422   * <p>It is imperative that the user manually synchronize on the returned deque when accessing any
423   * of the deque's iterators:
424   *
425   * <pre>{@code
426   * Deque<E> deque = Queues.synchronizedDeque(Queues.<E>newArrayDeque());
427   * ...
428   * deque.add(element);  // Needn't be in synchronized block
429   * ...
430   * synchronized (deque) {  // Must synchronize on deque!
431   *   Iterator<E> i = deque.iterator(); // Must be in synchronized block
432   *   while (i.hasNext()) {
433   *     foo(i.next());
434   *   }
435   * }
436   * }</pre>
437   *
438   * <p>Failure to follow this advice may result in non-deterministic behavior.
439   *
440   * <p>The returned deque will be serializable if the specified deque is serializable.
441   *
442   * @param deque the deque to be wrapped in a synchronized view
443   * @return a synchronized view of the specified deque
444   * @since 15.0
445   */
446  @J2ktIncompatible // Synchronized
447  public static <E extends @Nullable Object> Deque<E> synchronizedDeque(Deque<E> deque) {
448    return Synchronized.deque(deque, null);
449  }
450}