ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/BlockingQueue.java
Revision: 1.63
Committed: Mon Oct 1 00:10:53 2018 UTC (5 years, 7 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.62: +5 -5 lines
Log Message:
update to using jdk11 by default, except link to jdk10 javadocs;
sync @docRoot references in javadoc with upstream

File Contents

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