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 com.google.common.collect.Internal.toNanosSaturated; 018import static java.util.concurrent.TimeUnit.NANOSECONDS; 019 020import com.google.common.annotations.GwtCompatible; 021import com.google.common.annotations.GwtIncompatible; 022import com.google.common.annotations.J2ktIncompatible; 023import com.google.common.base.Preconditions; 024import com.google.errorprone.annotations.CanIgnoreReturnValue; 025import java.time.Duration; 026import java.util.ArrayDeque; 027import java.util.Collection; 028import java.util.Deque; 029import java.util.PriorityQueue; 030import java.util.Queue; 031import java.util.concurrent.ArrayBlockingQueue; 032import java.util.concurrent.BlockingQueue; 033import java.util.concurrent.ConcurrentLinkedQueue; 034import java.util.concurrent.LinkedBlockingDeque; 035import java.util.concurrent.LinkedBlockingQueue; 036import java.util.concurrent.PriorityBlockingQueue; 037import java.util.concurrent.SynchronousQueue; 038import java.util.concurrent.TimeUnit; 039import org.jspecify.annotations.Nullable; 040 041/** 042 * Static utility methods pertaining to {@link Queue} and {@link Deque} instances. Also see this 043 * class's counterparts {@link Lists}, {@link Sets}, and {@link Maps}. 044 * 045 * @author Kurt Alfred Kluever 046 * @since 11.0 047 */ 048@GwtCompatible 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 return drain(q, buffer, numElements, toNanosSaturated(timeout), 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 {@link #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 return drainUninterruptibly(q, buffer, numElements, toNanosSaturated(timeout), NANOSECONDS); 367 } 368 369 /** 370 * Drains the queue as {@link #drain(BlockingQueue, Collection, int, long, TimeUnit)}, but with a 371 * different behavior in case it is interrupted while waiting. In that case, the operation will 372 * continue as usual, and in the end the thread's interruption status will be set (no {@code 373 * InterruptedException} is thrown). 374 * 375 * @param q the blocking queue to be drained 376 * @param buffer where to add the transferred elements 377 * @param numElements the number of elements to be waited for 378 * @param timeout how long to wait before giving up, in units of {@code unit} 379 * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter 380 * @return the number of elements transferred 381 */ 382 @CanIgnoreReturnValue 383 @J2ktIncompatible 384 @GwtIncompatible // BlockingQueue 385 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 386 public static <E> int drainUninterruptibly( 387 BlockingQueue<E> q, 388 Collection<? super E> buffer, 389 int numElements, 390 long timeout, 391 TimeUnit unit) { 392 Preconditions.checkNotNull(buffer); 393 long deadline = System.nanoTime() + unit.toNanos(timeout); 394 int added = 0; 395 boolean interrupted = false; 396 try { 397 while (added < numElements) { 398 // we could rely solely on #poll, but #drainTo might be more efficient when there are 399 // multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) 400 added += q.drainTo(buffer, numElements - added); 401 if (added < numElements) { // not enough elements immediately available; will have to poll 402 E e; // written exactly once, by a successful (uninterrupted) invocation of #poll 403 while (true) { 404 try { 405 e = q.poll(deadline - System.nanoTime(), NANOSECONDS); 406 break; 407 } catch (InterruptedException ex) { 408 interrupted = true; // note interruption and retry 409 } 410 } 411 if (e == null) { 412 break; // we already waited enough, and there are no more elements in sight 413 } 414 buffer.add(e); 415 added++; 416 } 417 } 418 } finally { 419 if (interrupted) { 420 Thread.currentThread().interrupt(); 421 } 422 } 423 return added; 424 } 425 426 /** 427 * Returns a synchronized (thread-safe) queue backed by the specified queue. In order to guarantee 428 * serial access, it is critical that <b>all</b> access to the backing queue is accomplished 429 * through the returned queue. 430 * 431 * <p>It is imperative that the user manually synchronize on the returned queue when accessing the 432 * queue's iterator: 433 * 434 * {@snippet : 435 * Queue<E> queue = Queues.synchronizedQueue(MinMaxPriorityQueue.<E>create()); 436 * ... 437 * queue.add(element); // Needn't be in synchronized block 438 * ... 439 * synchronized (queue) { // Must synchronize on queue! 440 * Iterator<E> i = queue.iterator(); // Must be in synchronized block 441 * while (i.hasNext()) { 442 * foo(i.next()); 443 * } 444 * } 445 * } 446 * 447 * <p>Failure to follow this advice may result in non-deterministic behavior. 448 * 449 * <p>The returned queue will be serializable if the specified queue is serializable. 450 * 451 * @param queue the queue to be wrapped in a synchronized view 452 * @return a synchronized view of the specified queue 453 * @since 14.0 454 */ 455 @J2ktIncompatible // Synchronized 456 public static <E extends @Nullable Object> Queue<E> synchronizedQueue(Queue<E> queue) { 457 return Synchronized.queue(queue, null); 458 } 459 460 /** 461 * Returns a synchronized (thread-safe) deque backed by the specified deque. In order to guarantee 462 * serial access, it is critical that <b>all</b> access to the backing deque is accomplished 463 * through the returned deque. 464 * 465 * <p>It is imperative that the user manually synchronize on the returned deque when accessing any 466 * of the deque's iterators: 467 * 468 * {@snippet : 469 * Deque<E> deque = Queues.synchronizedDeque(Queues.newArrayDeque()); 470 * ... 471 * deque.add(element); // Needn't be in synchronized block 472 * ... 473 * synchronized (deque) { // Must synchronize on deque! 474 * Iterator<E> i = deque.iterator(); // Must be in synchronized block 475 * while (i.hasNext()) { 476 * foo(i.next()); 477 * } 478 * } 479 * } 480 * 481 * <p>Failure to follow this advice may result in non-deterministic behavior. 482 * 483 * <p>The returned deque will be serializable if the specified deque is serializable. 484 * 485 * @param deque the deque to be wrapped in a synchronized view 486 * @return a synchronized view of the specified deque 487 * @since 15.0 488 */ 489 @J2ktIncompatible // Synchronized 490 public static <E extends @Nullable Object> Deque<E> synchronizedDeque(Deque<E> deque) { 491 return Synchronized.deque(deque, null); 492 } 493}