Source for java.util.concurrent.BlockingQueue

   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/licenses/publicdomain
   5:  */
   6: 
   7: package java.util.concurrent;
   8: 
   9: import java.util.Collection;
  10: import java.util.Queue;
  11: 
  12: /**
  13:  * A {@link java.util.Queue} that additionally supports operations
  14:  * that wait for the queue to become non-empty when retrieving an
  15:  * element, and wait for space to become available in the queue when
  16:  * storing an element.
  17:  *
  18:  * <p><tt>BlockingQueue</tt> methods come in four forms, with different ways
  19:  * of handling operations that cannot be satisfied immediately, but may be
  20:  * satisfied at some point in the future:
  21:  * one throws an exception, the second returns a special value (either
  22:  * <tt>null</tt> or <tt>false</tt>, depending on the operation), the third
  23:  * blocks the current thread indefinitely until the operation can succeed,
  24:  * and the fourth blocks for only a given maximum time limit before giving
  25:  * up.  These methods are summarized in the following table:
  26:  *
  27:  * <p>
  28:  * <table BORDER CELLPADDING=3 CELLSPACING=1>
  29:  *  <tr>
  30:  *    <td></td>
  31:  *    <td ALIGN=CENTER><em>Throws exception</em></td>
  32:  *    <td ALIGN=CENTER><em>Special value</em></td>
  33:  *    <td ALIGN=CENTER><em>Blocks</em></td>
  34:  *    <td ALIGN=CENTER><em>Times out</em></td>
  35:  *  </tr>
  36:  *  <tr>
  37:  *    <td><b>Insert</b></td>
  38:  *    <td>{@link #add add(e)}</td>
  39:  *    <td>{@link #offer offer(e)}</td>
  40:  *    <td>{@link #put put(e)}</td>
  41:  *    <td>{@link #offer(Object, long, TimeUnit) offer(e, time, unit)}</td>
  42:  *  </tr>
  43:  *  <tr>
  44:  *    <td><b>Remove</b></td>
  45:  *    <td>{@link #remove remove()}</td>
  46:  *    <td>{@link #poll poll()}</td>
  47:  *    <td>{@link #take take()}</td>
  48:  *    <td>{@link #poll(long, TimeUnit) poll(time, unit)}</td>
  49:  *  </tr>
  50:  *  <tr>
  51:  *    <td><b>Examine</b></td>
  52:  *    <td>{@link #element element()}</td>
  53:  *    <td>{@link #peek peek()}</td>
  54:  *    <td><em>not applicable</em></td>
  55:  *    <td><em>not applicable</em></td>
  56:  *  </tr>
  57:  * </table>
  58:  *
  59:  * <p>A <tt>BlockingQueue</tt> does not accept <tt>null</tt> elements.
  60:  * Implementations throw <tt>NullPointerException</tt> on attempts
  61:  * to <tt>add</tt>, <tt>put</tt> or <tt>offer</tt> a <tt>null</tt>.  A
  62:  * <tt>null</tt> is used as a sentinel value to indicate failure of
  63:  * <tt>poll</tt> operations.
  64:  *
  65:  * <p>A <tt>BlockingQueue</tt> may be capacity bounded. At any given
  66:  * time it may have a <tt>remainingCapacity</tt> beyond which no
  67:  * additional elements can be <tt>put</tt> without blocking.
  68:  * A <tt>BlockingQueue</tt> without any intrinsic capacity constraints always
  69:  * reports a remaining capacity of <tt>Integer.MAX_VALUE</tt>.
  70:  *
  71:  * <p> <tt>BlockingQueue</tt> implementations are designed to be used
  72:  * primarily for producer-consumer queues, but additionally support
  73:  * the {@link java.util.Collection} interface.  So, for example, it is
  74:  * possible to remove an arbitrary element from a queue using
  75:  * <tt>remove(x)</tt>. However, such operations are in general
  76:  * <em>not</em> performed very efficiently, and are intended for only
  77:  * occasional use, such as when a queued message is cancelled.
  78:  *
  79:  * <p> <tt>BlockingQueue</tt> implementations are thread-safe.  All
  80:  * queuing methods achieve their effects atomically using internal
  81:  * locks or other forms of concurrency control. However, the
  82:  * <em>bulk</em> Collection operations <tt>addAll</tt>,
  83:  * <tt>containsAll</tt>, <tt>retainAll</tt> and <tt>removeAll</tt> are
  84:  * <em>not</em> necessarily performed atomically unless specified
  85:  * otherwise in an implementation. So it is possible, for example, for
  86:  * <tt>addAll(c)</tt> to fail (throwing an exception) after adding
  87:  * only some of the elements in <tt>c</tt>.
  88:  *
  89:  * <p>A <tt>BlockingQueue</tt> does <em>not</em> intrinsically support
  90:  * any kind of &quot;close&quot; or &quot;shutdown&quot; operation to
  91:  * indicate that no more items will be added.  The needs and usage of
  92:  * such features tend to be implementation-dependent. For example, a
  93:  * common tactic is for producers to insert special
  94:  * <em>end-of-stream</em> or <em>poison</em> objects, that are
  95:  * interpreted accordingly when taken by consumers.
  96:  *
  97:  * <p>
  98:  * Usage example, based on a typical producer-consumer scenario.
  99:  * Note that a <tt>BlockingQueue</tt> can safely be used with multiple
 100:  * producers and multiple consumers.
 101:  * <pre>
 102:  * class Producer implements Runnable {
 103:  *   private final BlockingQueue queue;
 104:  *   Producer(BlockingQueue q) { queue = q; }
 105:  *   public void run() {
 106:  *     try {
 107:  *       while (true) { queue.put(produce()); }
 108:  *     } catch (InterruptedException ex) { ... handle ...}
 109:  *   }
 110:  *   Object produce() { ... }
 111:  * }
 112:  *
 113:  * class Consumer implements Runnable {
 114:  *   private final BlockingQueue queue;
 115:  *   Consumer(BlockingQueue q) { queue = q; }
 116:  *   public void run() {
 117:  *     try {
 118:  *       while (true) { consume(queue.take()); }
 119:  *     } catch (InterruptedException ex) { ... handle ...}
 120:  *   }
 121:  *   void consume(Object x) { ... }
 122:  * }
 123:  *
 124:  * class Setup {
 125:  *   void main() {
 126:  *     BlockingQueue q = new SomeQueueImplementation();
 127:  *     Producer p = new Producer(q);
 128:  *     Consumer c1 = new Consumer(q);
 129:  *     Consumer c2 = new Consumer(q);
 130:  *     new Thread(p).start();
 131:  *     new Thread(c1).start();
 132:  *     new Thread(c2).start();
 133:  *   }
 134:  * }
 135:  * </pre>
 136:  *
 137:  * <p>Memory consistency effects: As with other concurrent
 138:  * collections, actions in a thread prior to placing an object into a
 139:  * {@code BlockingQueue}
 140:  * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
 141:  * actions subsequent to the access or removal of that element from
 142:  * the {@code BlockingQueue} in another thread.
 143:  *
 144:  * <p>This interface is a member of the
 145:  * <a href="{@docRoot}/../technotes/guides/collections/index.html">
 146:  * Java Collections Framework</a>.
 147:  *
 148:  * @since 1.5
 149:  * @author Doug Lea
 150:  * @param <E> the type of elements held in this collection
 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:      * <tt>true</tt> upon success and throwing an
 157:      * <tt>IllegalStateException</tt> 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 <tt>true</tt> (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:      */
 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:      * <tt>true</tt> upon success and <tt>false</tt> 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 <tt>true</tt> if the element was added to this queue, else
 183:      *         <tt>false</tt>
 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:      */
 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:      */
 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:      *        <tt>unit</tt>
 213:      * @param unit a <tt>TimeUnit</tt> determining how to interpret the
 214:      *        <tt>timeout</tt> parameter
 215:      * @return <tt>true</tt> if successful, or <tt>false</tt> 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:      */
 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:      */
 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:      *        <tt>unit</tt>
 242:      * @param unit a <tt>TimeUnit</tt> determining how to interpret the
 243:      *        <tt>timeout</tt> parameter
 244:      * @return the head of this queue, or <tt>null</tt> if the
 245:      *         specified waiting time elapses before an element is available
 246:      * @throws InterruptedException if interrupted while waiting
 247:      */
 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 <tt>Integer.MAX_VALUE</tt> 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 <tt>remainingCapacity</tt>
 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:      */
 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 <tt>e</tt> such
 269:      * that <tt>o.equals(e)</tt>, if this queue contains one or more such
 270:      * elements.
 271:      * Returns <tt>true</tt> 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 <tt>true</tt> 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 (optional)
 278:      * @throws NullPointerException if the specified element is null (optional)
 279:      */
 280:     boolean remove(Object o);
 281: 
 282:     /**
 283:      * Returns <tt>true</tt> if this queue contains the specified element.
 284:      * More formally, returns <tt>true</tt> if and only if this queue contains
 285:      * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
 286:      *
 287:      * @param o object to be checked for containment in this queue
 288:      * @return <tt>true</tt> if this queue contains the specified element
 289:      * @throws ClassCastException if the class of the specified element
 290:      *         is incompatible with this queue (optional)
 291:      * @throws NullPointerException if the specified element is null (optional)
 292:      */
 293:     public boolean contains(Object o);
 294: 
 295:     /**
 296:      * Removes all available elements from this queue and adds them
 297:      * to the given collection.  This operation may be more
 298:      * efficient than repeatedly polling this queue.  A failure
 299:      * encountered while attempting to add elements to
 300:      * collection <tt>c</tt> may result in elements being in neither,
 301:      * either or both collections when the associated exception is
 302:      * thrown.  Attempts to drain a queue to itself result in
 303:      * <tt>IllegalArgumentException</tt>. Further, the behavior of
 304:      * this operation is undefined if the specified collection is
 305:      * modified while the operation is in progress.
 306:      *
 307:      * @param c the collection to transfer elements into
 308:      * @return the number of elements transferred
 309:      * @throws UnsupportedOperationException if addition of elements
 310:      *         is not supported by the specified collection
 311:      * @throws ClassCastException if the class of an element of this queue
 312:      *         prevents it from being added to the specified collection
 313:      * @throws NullPointerException if the specified collection is null
 314:      * @throws IllegalArgumentException if the specified collection is this
 315:      *         queue, or some property of an element of this queue prevents
 316:      *         it from being added to the specified collection
 317:      */
 318:     int drainTo(Collection<? super E> c);
 319: 
 320:     /**
 321:      * Removes at most the given number of available elements from
 322:      * this queue and adds them to the given collection.  A failure
 323:      * encountered while attempting to add elements to
 324:      * collection <tt>c</tt> may result in elements being in neither,
 325:      * either or both collections when the associated exception is
 326:      * thrown.  Attempts to drain a queue to itself result in
 327:      * <tt>IllegalArgumentException</tt>. Further, the behavior of
 328:      * this operation is undefined if the specified collection is
 329:      * modified while the operation is in progress.
 330:      *
 331:      * @param c the collection to transfer elements into
 332:      * @param maxElements the maximum number of elements to transfer
 333:      * @return the number of elements transferred
 334:      * @throws UnsupportedOperationException if addition of elements
 335:      *         is not supported by the specified collection
 336:      * @throws ClassCastException if the class of an element of this queue
 337:      *         prevents it from being added to the specified collection
 338:      * @throws NullPointerException if the specified collection is null
 339:      * @throws IllegalArgumentException if the specified collection is this
 340:      *         queue, or some property of an element of this queue prevents
 341:      *         it from being added to the specified collection
 342:      */
 343:     int drainTo(Collection<? super E> c, int maxElements);
 344: }