1 /* 2 * Written by Doug Lea with assistance from members of JCP JSR-166 3 * Expert Group and released to the public domain, as explained at 4 * http://creativecommons.org/publicdomain/zero/1.0/ 5 */ 6 7 package java.util.concurrent; 8 9 import java.util.Collection; 10 import java.util.Queue; 11 12 // BEGIN android-note 13 // removed link to collections framework docs from header 14 // fixed framework docs link to "Collection#optional" 15 // END android-note 16 17 /** 18 * A {@link java.util.Queue} that additionally supports operations 19 * that wait for the queue to become non-empty when retrieving an 20 * element, and wait for space to become available in the queue when 21 * storing an element. 22 * 23 * <p>{@code BlockingQueue} methods come in four forms, with different ways 24 * of handling operations that cannot be satisfied immediately, but may be 25 * satisfied at some point in the future: 26 * one throws an exception, the second returns a special value (either 27 * {@code null} or {@code false}, depending on the operation), the third 28 * blocks the current thread indefinitely until the operation can succeed, 29 * and the fourth blocks for only a given maximum time limit before giving 30 * up. These methods are summarized in the following table: 31 * 32 * <table BORDER CELLPADDING=3 CELLSPACING=1> 33 * <caption>Summary of BlockingQueue methods</caption> 34 * <tr> 35 * <td></td> 36 * <td ALIGN=CENTER><em>Throws exception</em></td> 37 * <td ALIGN=CENTER><em>Special value</em></td> 38 * <td ALIGN=CENTER><em>Blocks</em></td> 39 * <td ALIGN=CENTER><em>Times out</em></td> 40 * </tr> 41 * <tr> 42 * <td><b>Insert</b></td> 43 * <td>{@link #add add(e)}</td> 44 * <td>{@link #offer offer(e)}</td> 45 * <td>{@link #put put(e)}</td> 46 * <td>{@link #offer(Object, long, TimeUnit) offer(e, time, unit)}</td> 47 * </tr> 48 * <tr> 49 * <td><b>Remove</b></td> 50 * <td>{@link #remove remove()}</td> 51 * <td>{@link #poll poll()}</td> 52 * <td>{@link #take take()}</td> 53 * <td>{@link #poll(long, TimeUnit) poll(time, unit)}</td> 54 * </tr> 55 * <tr> 56 * <td><b>Examine</b></td> 57 * <td>{@link #element element()}</td> 58 * <td>{@link #peek peek()}</td> 59 * <td><em>not applicable</em></td> 60 * <td><em>not applicable</em></td> 61 * </tr> 62 * </table> 63 * 64 * <p>A {@code BlockingQueue} does not accept {@code null} elements. 65 * Implementations throw {@code NullPointerException} on attempts 66 * to {@code add}, {@code put} or {@code offer} a {@code null}. A 67 * {@code null} is used as a sentinel value to indicate failure of 68 * {@code poll} operations. 69 * 70 * <p>A {@code BlockingQueue} may be capacity bounded. At any given 71 * time it may have a {@code remainingCapacity} beyond which no 72 * additional elements can be {@code put} without blocking. 73 * A {@code BlockingQueue} without any intrinsic capacity constraints always 74 * reports a remaining capacity of {@code Integer.MAX_VALUE}. 75 * 76 * <p>{@code BlockingQueue} implementations are designed to be used 77 * primarily for producer-consumer queues, but additionally support 78 * the {@link java.util.Collection} interface. So, for example, it is 79 * possible to remove an arbitrary element from a queue using 80 * {@code remove(x)}. However, such operations are in general 81 * <em>not</em> performed very efficiently, and are intended for only 82 * occasional use, such as when a queued message is cancelled. 83 * 84 * <p>{@code BlockingQueue} implementations are thread-safe. All 85 * queuing methods achieve their effects atomically using internal 86 * locks or other forms of concurrency control. However, the 87 * <em>bulk</em> Collection operations {@code addAll}, 88 * {@code containsAll}, {@code retainAll} and {@code removeAll} are 89 * <em>not</em> necessarily performed atomically unless specified 90 * otherwise in an implementation. So it is possible, for example, for 91 * {@code addAll(c)} to fail (throwing an exception) after adding 92 * only some of the elements in {@code c}. 93 * 94 * <p>A {@code BlockingQueue} does <em>not</em> intrinsically support 95 * any kind of "close" or "shutdown" operation to 96 * indicate that no more items will be added. The needs and usage of 97 * such features tend to be implementation-dependent. For example, a 98 * common tactic is for producers to insert special 99 * <em>end-of-stream</em> or <em>poison</em> objects, that are 100 * interpreted accordingly when taken by consumers. 101 * 102 * <p> 103 * Usage example, based on a typical producer-consumer scenario. 104 * Note that a {@code BlockingQueue} can safely be used with multiple 105 * producers and multiple consumers. 106 * <pre> {@code 107 * class Producer implements Runnable { 108 * private final BlockingQueue queue; 109 * Producer(BlockingQueue q) { queue = q; } 110 * public void run() { 111 * try { 112 * while (true) { queue.put(produce()); } 113 * } catch (InterruptedException ex) { ... handle ...} 114 * } 115 * Object produce() { ... } 116 * } 117 * 118 * class Consumer implements Runnable { 119 * private final BlockingQueue queue; 120 * Consumer(BlockingQueue q) { queue = q; } 121 * public void run() { 122 * try { 123 * while (true) { consume(queue.take()); } 124 * } catch (InterruptedException ex) { ... handle ...} 125 * } 126 * void consume(Object x) { ... } 127 * } 128 * 129 * class Setup { 130 * void main() { 131 * BlockingQueue q = new SomeQueueImplementation(); 132 * Producer p = new Producer(q); 133 * Consumer c1 = new Consumer(q); 134 * Consumer c2 = new Consumer(q); 135 * new Thread(p).start(); 136 * new Thread(c1).start(); 137 * new Thread(c2).start(); 138 * } 139 * }}</pre> 140 * 141 * <p>Memory consistency effects: As with other concurrent 142 * collections, actions in a thread prior to placing an object into a 143 * {@code BlockingQueue} 144 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a> 145 * actions subsequent to the access or removal of that element from 146 * the {@code BlockingQueue} in another thread. 147 * 148 * @since 1.5 149 * @author Doug Lea 150 * @param <E> the type of elements held in this queue 151 */ 152 public interface BlockingQueue<E> extends Queue<E> { 153 /** 154 * Inserts the specified element into this queue if it is possible to do 155 * so immediately without violating capacity restrictions, returning 156 * {@code true} upon success and throwing an 157 * {@code IllegalStateException} if no space is currently available. 158 * When using a capacity-restricted queue, it is generally preferable to 159 * use {@link #offer(Object) offer}. 160 * 161 * @param e the element to add 162 * @return {@code true} (as specified by {@link Collection#add}) 163 * @throws IllegalStateException if the element cannot be added at this 164 * time due to capacity restrictions 165 * @throws ClassCastException if the class of the specified element 166 * prevents it from being added to this queue 167 * @throws NullPointerException if the specified element is null 168 * @throws IllegalArgumentException if some property of the specified 169 * element prevents it from being added to this queue 170 */ add(E e)171 boolean add(E e); 172 173 /** 174 * Inserts the specified element into this queue if it is possible to do 175 * so immediately without violating capacity restrictions, returning 176 * {@code true} upon success and {@code false} if no space is currently 177 * available. When using a capacity-restricted queue, this method is 178 * generally preferable to {@link #add}, which can fail to insert an 179 * element only by throwing an exception. 180 * 181 * @param e the element to add 182 * @return {@code true} if the element was added to this queue, else 183 * {@code false} 184 * @throws ClassCastException if the class of the specified element 185 * prevents it from being added to this queue 186 * @throws NullPointerException if the specified element is null 187 * @throws IllegalArgumentException if some property of the specified 188 * element prevents it from being added to this queue 189 */ offer(E e)190 boolean offer(E e); 191 192 /** 193 * Inserts the specified element into this queue, waiting if necessary 194 * for space to become available. 195 * 196 * @param e the element to add 197 * @throws InterruptedException if interrupted while waiting 198 * @throws ClassCastException if the class of the specified element 199 * prevents it from being added to this queue 200 * @throws NullPointerException if the specified element is null 201 * @throws IllegalArgumentException if some property of the specified 202 * element prevents it from being added to this queue 203 */ put(E e)204 void put(E e) throws InterruptedException; 205 206 /** 207 * Inserts the specified element into this queue, waiting up to the 208 * specified wait time if necessary for space to become available. 209 * 210 * @param e the element to add 211 * @param timeout how long to wait before giving up, in units of 212 * {@code unit} 213 * @param unit a {@code TimeUnit} determining how to interpret the 214 * {@code timeout} parameter 215 * @return {@code true} if successful, or {@code false} if 216 * the specified waiting time elapses before space is available 217 * @throws InterruptedException if interrupted while waiting 218 * @throws ClassCastException if the class of the specified element 219 * prevents it from being added to this queue 220 * @throws NullPointerException if the specified element is null 221 * @throws IllegalArgumentException if some property of the specified 222 * element prevents it from being added to this queue 223 */ offer(E e, long timeout, TimeUnit unit)224 boolean offer(E e, long timeout, TimeUnit unit) 225 throws InterruptedException; 226 227 /** 228 * Retrieves and removes the head of this queue, waiting if necessary 229 * until an element becomes available. 230 * 231 * @return the head of this queue 232 * @throws InterruptedException if interrupted while waiting 233 */ take()234 E take() throws InterruptedException; 235 236 /** 237 * Retrieves and removes the head of this queue, waiting up to the 238 * specified wait time if necessary for an element to become available. 239 * 240 * @param timeout how long to wait before giving up, in units of 241 * {@code unit} 242 * @param unit a {@code TimeUnit} determining how to interpret the 243 * {@code timeout} parameter 244 * @return the head of this queue, or {@code null} if the 245 * specified waiting time elapses before an element is available 246 * @throws InterruptedException if interrupted while waiting 247 */ poll(long timeout, TimeUnit unit)248 E poll(long timeout, TimeUnit unit) 249 throws InterruptedException; 250 251 /** 252 * Returns the number of additional elements that this queue can ideally 253 * (in the absence of memory or resource constraints) accept without 254 * blocking, or {@code Integer.MAX_VALUE} if there is no intrinsic 255 * limit. 256 * 257 * <p>Note that you <em>cannot</em> always tell if an attempt to insert 258 * an element will succeed by inspecting {@code remainingCapacity} 259 * because it may be the case that another thread is about to 260 * insert or remove an element. 261 * 262 * @return the remaining capacity 263 */ remainingCapacity()264 int remainingCapacity(); 265 266 /** 267 * Removes a single instance of the specified element from this queue, 268 * if it is present. More formally, removes an element {@code e} such 269 * that {@code o.equals(e)}, if this queue contains one or more such 270 * elements. 271 * Returns {@code true} if this queue contained the specified element 272 * (or equivalently, if this queue changed as a result of the call). 273 * 274 * @param o element to be removed from this queue, if present 275 * @return {@code true} if this queue changed as a result of the call 276 * @throws ClassCastException if the class of the specified element 277 * is incompatible with this queue 278 * (<a href="../Collection.html#optional-restrictions">optional</a>) 279 * @throws NullPointerException if the specified element is null 280 * (<a href="../Collection.html#optional-restrictions">optional</a>) 281 */ remove(Object o)282 boolean remove(Object o); 283 284 /** 285 * Returns {@code true} if this queue contains the specified element. 286 * More formally, returns {@code true} if and only if this queue contains 287 * at least one element {@code e} such that {@code o.equals(e)}. 288 * 289 * @param o object to be checked for containment in this queue 290 * @return {@code true} if this queue contains the specified element 291 * @throws ClassCastException if the class of the specified element 292 * is incompatible with this queue 293 * (<a href="../Collection.html#optional-restrictions">optional</a>) 294 * @throws NullPointerException if the specified element is null 295 * (<a href="../Collection.html#optional-restrictions">optional</a>) 296 */ contains(Object o)297 boolean contains(Object o); 298 299 /** 300 * Removes all available elements from this queue and adds them 301 * to the given collection. This operation may be more 302 * efficient than repeatedly polling this queue. A failure 303 * encountered while attempting to add elements to 304 * collection {@code c} may result in elements being in neither, 305 * either or both collections when the associated exception is 306 * thrown. Attempts to drain a queue to itself result in 307 * {@code IllegalArgumentException}. Further, the behavior of 308 * this operation is undefined if the specified collection is 309 * modified while the operation is in progress. 310 * 311 * @param c the collection to transfer elements into 312 * @return the number of elements transferred 313 * @throws UnsupportedOperationException if addition of elements 314 * is not supported by the specified collection 315 * @throws ClassCastException if the class of an element of this queue 316 * prevents it from being added to the specified collection 317 * @throws NullPointerException if the specified collection is null 318 * @throws IllegalArgumentException if the specified collection is this 319 * queue, or some property of an element of this queue prevents 320 * it from being added to the specified collection 321 */ drainTo(Collection<? super E> c)322 int drainTo(Collection<? super E> c); 323 324 /** 325 * Removes at most the given number of available elements from 326 * this queue and adds them to the given collection. A failure 327 * encountered while attempting to add elements to 328 * collection {@code c} may result in elements being in neither, 329 * either or both collections when the associated exception is 330 * thrown. Attempts to drain a queue to itself result in 331 * {@code IllegalArgumentException}. Further, the behavior of 332 * this operation is undefined if the specified collection is 333 * modified while the operation is in progress. 334 * 335 * @param c the collection to transfer elements into 336 * @param maxElements the maximum number of elements to transfer 337 * @return the number of elements transferred 338 * @throws UnsupportedOperationException if addition of elements 339 * is not supported by the specified collection 340 * @throws ClassCastException if the class of an element of this queue 341 * prevents it from being added to the specified collection 342 * @throws NullPointerException if the specified collection is null 343 * @throws IllegalArgumentException if the specified collection is this 344 * queue, or some property of an element of this queue prevents 345 * it from being added to the specified collection 346 */ drainTo(Collection<? super E> c, int maxElements)347 int drainTo(Collection<? super E> c, int maxElements); 348 } 349