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