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