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