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.Beta; 018import com.google.common.base.Preconditions; 019 020import java.util.Collection; 021import java.util.PriorityQueue; 022import java.util.Queue; 023import java.util.concurrent.ArrayBlockingQueue; 024import java.util.concurrent.BlockingQueue; 025import java.util.concurrent.ConcurrentLinkedQueue; 026import java.util.concurrent.LinkedBlockingQueue; 027import java.util.concurrent.PriorityBlockingQueue; 028import java.util.concurrent.SynchronousQueue; 029import java.util.concurrent.TimeUnit; 030 031/** 032 * Static utility methods pertaining to {@link Queue} instances. 033 * Also see this class's counterparts {@link Lists}, {@link Sets}, and {@link Maps}. 034 * 035 * @author Kurt Alfred Kluever 036 * @since 11.0 037 */ 038public final class Queues { 039 private Queues() {} 040 041 // ArrayBlockingQueue 042 043 /** 044 * Creates an empty {@code ArrayBlockingQueue} with the given (fixed) capacity 045 * and nonfair access policy. 046 */ 047 public static <E> ArrayBlockingQueue<E> newArrayBlockingQueue(int capacity) { 048 return new ArrayBlockingQueue<E>(capacity); 049 } 050 051 // ConcurrentLinkedQueue 052 053 /** 054 * Creates an empty {@code ConcurrentLinkedQueue}. 055 */ 056 public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue() { 057 return new ConcurrentLinkedQueue<E>(); 058 } 059 060 /** 061 * Creates a {@code ConcurrentLinkedQueue} containing the elements of the specified iterable, 062 * in the order they are returned by the iterable's iterator. 063 */ 064 public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue( 065 Iterable<? extends E> elements) { 066 if (elements instanceof Collection) { 067 return new ConcurrentLinkedQueue<E>(Collections2.cast(elements)); 068 } 069 ConcurrentLinkedQueue<E> queue = new ConcurrentLinkedQueue<E>(); 070 Iterables.addAll(queue, elements); 071 return queue; 072 } 073 074 // LinkedBlockingQueue 075 076 /** 077 * Creates an empty {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}. 078 */ 079 public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue() { 080 return new LinkedBlockingQueue<E>(); 081 } 082 083 /** 084 * Creates an empty {@code LinkedBlockingQueue} with the given (fixed) capacity. 085 * 086 * @throws IllegalArgumentException if {@code capacity} is less than 1 087 */ 088 public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(int capacity) { 089 return new LinkedBlockingQueue<E>(capacity); 090 } 091 092 /** 093 * Creates a {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}, 094 * containing the elements of the specified iterable, 095 * in the order they are returned by the iterable's iterator. 096 * 097 * @param elements the elements that the queue should contain, in order 098 * @return a new {@code LinkedBlockingQueue} containing those elements 099 */ 100 public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(Iterable<? extends E> elements) { 101 if (elements instanceof Collection) { 102 return new LinkedBlockingQueue<E>(Collections2.cast(elements)); 103 } 104 LinkedBlockingQueue<E> queue = new LinkedBlockingQueue<E>(); 105 Iterables.addAll(queue, elements); 106 return queue; 107 } 108 109 // LinkedList: see {@link com.google.common.collect.Lists} 110 111 // PriorityBlockingQueue 112 113 /** 114 * Creates an empty {@code PriorityBlockingQueue} with the ordering given by its 115 * elements' natural ordering. 116 * 117 * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). 118 */ 119 public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue() { 120 return new PriorityBlockingQueue<E>(); 121 } 122 123 /** 124 * Creates a {@code PriorityBlockingQueue} containing the given elements. 125 * 126 * <b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue}, 127 * this priority queue will be ordered according to the same ordering. 128 * 129 * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). 130 */ 131 public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue( 132 Iterable<? extends E> elements) { 133 if (elements instanceof Collection) { 134 return new PriorityBlockingQueue<E>(Collections2.cast(elements)); 135 } 136 PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<E>(); 137 Iterables.addAll(queue, elements); 138 return queue; 139 } 140 141 // PriorityQueue 142 143 /** 144 * Creates an empty {@code PriorityQueue} with the ordering given by its 145 * elements' natural ordering. 146 * 147 * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). 148 */ 149 public static <E extends Comparable> PriorityQueue<E> newPriorityQueue() { 150 return new PriorityQueue<E>(); 151 } 152 153 /** 154 * Creates a {@code PriorityQueue} containing the given elements. 155 * 156 * <b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue}, 157 * this priority queue will be ordered according to the same ordering. 158 * 159 * @since 11.0 (requires that {@code E} be {@code Comparable} since 15.0). 160 */ 161 public static <E extends Comparable> PriorityQueue<E> newPriorityQueue( 162 Iterable<? extends E> elements) { 163 if (elements instanceof Collection) { 164 return new PriorityQueue<E>(Collections2.cast(elements)); 165 } 166 PriorityQueue<E> queue = new PriorityQueue<E>(); 167 Iterables.addAll(queue, elements); 168 return queue; 169 } 170 171 // SynchronousQueue 172 173 /** 174 * Creates an empty {@code SynchronousQueue} with nonfair access policy. 175 */ 176 public static <E> SynchronousQueue<E> newSynchronousQueue() { 177 return new SynchronousQueue<E>(); 178 } 179 180 /** 181 * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested 182 * {@code numElements} elements are not available, it will wait for them up to the specified 183 * timeout. 184 * 185 * @param q the blocking queue to be drained 186 * @param buffer where to add the transferred elements 187 * @param numElements the number of elements to be waited for 188 * @param timeout how long to wait before giving up, in units of {@code unit} 189 * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter 190 * @return the number of elements transferred 191 * @throws InterruptedException if interrupted while waiting 192 */ 193 @Beta 194 public static <E> int drain(BlockingQueue<E> q, Collection<? super E> buffer, int numElements, 195 long timeout, TimeUnit unit) throws InterruptedException { 196 Preconditions.checkNotNull(buffer); 197 /* 198 * This code performs one System.nanoTime() more than necessary, and in return, the time to 199 * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make 200 * the timeout arbitrarily inaccurate, given a queue that is slow to drain). 201 */ 202 long deadline = System.nanoTime() + unit.toNanos(timeout); 203 int added = 0; 204 while (added < numElements) { 205 // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple 206 // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) 207 added += q.drainTo(buffer, numElements - added); 208 if (added < numElements) { // not enough elements immediately available; will have to poll 209 E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); 210 if (e == null) { 211 break; // we already waited enough, and there are no more elements in sight 212 } 213 buffer.add(e); 214 added++; 215 } 216 } 217 return added; 218 } 219 220 /** 221 * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)}, 222 * but with a different behavior in case it is interrupted while waiting. In that case, the 223 * operation will continue as usual, and in the end the thread's interruption status will be set 224 * (no {@code InterruptedException} is thrown). 225 * 226 * @param q the blocking queue to be drained 227 * @param buffer where to add the transferred elements 228 * @param numElements the number of elements to be waited for 229 * @param timeout how long to wait before giving up, in units of {@code unit} 230 * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter 231 * @return the number of elements transferred 232 */ 233 @Beta 234 public static <E> int drainUninterruptibly(BlockingQueue<E> q, Collection<? super E> buffer, 235 int numElements, long timeout, TimeUnit unit) { 236 Preconditions.checkNotNull(buffer); 237 long deadline = System.nanoTime() + unit.toNanos(timeout); 238 int added = 0; 239 boolean interrupted = false; 240 try { 241 while (added < numElements) { 242 // we could rely solely on #poll, but #drainTo might be more efficient when there are 243 // multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) 244 added += q.drainTo(buffer, numElements - added); 245 if (added < numElements) { // not enough elements immediately available; will have to poll 246 E e; // written exactly once, by a successful (uninterrupted) invocation of #poll 247 while (true) { 248 try { 249 e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); 250 break; 251 } catch (InterruptedException ex) { 252 interrupted = true; // note interruption and retry 253 } 254 } 255 if (e == null) { 256 break; // we already waited enough, and there are no more elements in sight 257 } 258 buffer.add(e); 259 added++; 260 } 261 } 262 } finally { 263 if (interrupted) { 264 Thread.currentThread().interrupt(); 265 } 266 } 267 return added; 268 } 269 270 /** 271 * Returns a synchronized (thread-safe) queue backed by the specified queue. In order to 272 * guarantee serial access, it is critical that <b>all</b> access to the backing queue is 273 * accomplished through the returned queue. 274 * 275 * <p>It is imperative that the user manually synchronize on the returned queue when accessing 276 * the queue's iterator: <pre> {@code 277 * 278 * Queue<E> queue = Queues.synchronizedQueue(MinMaxPriorityQueue.<E>create()); 279 * ... 280 * queue.add(element); // Needn't be in synchronized block 281 * ... 282 * synchronized (queue) { // Must synchronize on queue! 283 * Iterator<E> i = queue.iterator(); // Must be in synchronized block 284 * while (i.hasNext()) { 285 * foo(i.next()); 286 * } 287 * }}</pre> 288 * 289 * <p>Failure to follow this advice may result in non-deterministic behavior. 290 * 291 * <p>The returned queue will be serializable if the specified queue is serializable. 292 * 293 * @param queue the queue to be wrapped in a synchronized view 294 * @return a synchronized view of the specified queue 295 * @since 14.0 296 */ 297 @Beta 298 public static <E> Queue<E> synchronizedQueue(Queue<E> queue) { 299 return Synchronized.queue(queue, null); 300 } 301}