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