BlockingQueue.java revision 51b1b6997fd3f980076b8081f7f1165ccc2a4008
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
36package java.util.concurrent;
37
38import java.util.Collection;
39import 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><tt>BlockingQueue</tt> 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 * <tt>null</tt> or <tt>false</tt>, 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 * <p>
57 * <table BORDER CELLPADDING=3 CELLSPACING=1>
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 <tt>BlockingQueue</tt> does not accept <tt>null</tt> elements.
89 * Implementations throw <tt>NullPointerException</tt> on attempts
90 * to <tt>add</tt>, <tt>put</tt> or <tt>offer</tt> a <tt>null</tt>.  A
91 * <tt>null</tt> is used as a sentinel value to indicate failure of
92 * <tt>poll</tt> operations.
93 *
94 * <p>A <tt>BlockingQueue</tt> may be capacity bounded. At any given
95 * time it may have a <tt>remainingCapacity</tt> beyond which no
96 * additional elements can be <tt>put</tt> without blocking.
97 * A <tt>BlockingQueue</tt> without any intrinsic capacity constraints always
98 * reports a remaining capacity of <tt>Integer.MAX_VALUE</tt>.
99 *
100 * <p> <tt>BlockingQueue</tt> 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 * <tt>remove(x)</tt>. 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> <tt>BlockingQueue</tt> 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 <tt>addAll</tt>,
112 * <tt>containsAll</tt>, <tt>retainAll</tt> and <tt>removeAll</tt> are
113 * <em>not</em> necessarily performed atomically unless specified
114 * otherwise in an implementation. So it is possible, for example, for
115 * <tt>addAll(c)</tt> to fail (throwing an exception) after adding
116 * only some of the elements in <tt>c</tt>.
117 *
118 * <p>A <tt>BlockingQueue</tt> 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 <tt>BlockingQueue</tt> can safely be used with multiple
129 * producers and multiple consumers.
130 * <pre>
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 * }
164 * </pre>
165 *
166 * <p>Memory consistency effects: As with other concurrent
167 * collections, actions in a thread prior to placing an object into a
168 * {@code BlockingQueue}
169 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
170 * actions subsequent to the access or removal of that element from
171 * the {@code BlockingQueue} in another thread.
172 *
173 * <p>This interface is a member of the
174 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
175 * Java Collections Framework</a>.
176 *
177 * @since 1.5
178 * @author Doug Lea
179 * @param <E> the type of elements held in this collection
180 */
181public 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     * <tt>true</tt> upon success and throwing an
186     * <tt>IllegalStateException</tt> 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 <tt>true</tt> (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     */
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     * <tt>true</tt> upon success and <tt>false</tt> 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 <tt>true</tt> if the element was added to this queue, else
212     *         <tt>false</tt>
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     */
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     */
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     *        <tt>unit</tt>
242     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
243     *        <tt>timeout</tt> parameter
244     * @return <tt>true</tt> if successful, or <tt>false</tt> 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     */
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     */
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     *        <tt>unit</tt>
271     * @param unit a <tt>TimeUnit</tt> determining how to interpret the
272     *        <tt>timeout</tt> parameter
273     * @return the head of this queue, or <tt>null</tt> if the
274     *         specified waiting time elapses before an element is available
275     * @throws InterruptedException if interrupted while waiting
276     */
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 <tt>Integer.MAX_VALUE</tt> 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 <tt>remainingCapacity</tt>
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     */
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 <tt>e</tt> such
298     * that <tt>o.equals(e)</tt>, if this queue contains one or more such
299     * elements.
300     * Returns <tt>true</tt> 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 <tt>true</tt> 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     */
311    boolean remove(Object o);
312
313    /**
314     * Returns <tt>true</tt> if this queue contains the specified element.
315     * More formally, returns <tt>true</tt> if and only if this queue contains
316     * at least one element <tt>e</tt> such that <tt>o.equals(e)</tt>.
317     *
318     * @param o object to be checked for containment in this queue
319     * @return <tt>true</tt> 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     */
326    public 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 <tt>c</tt> 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     * <tt>IllegalArgumentException</tt>. 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     */
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 <tt>c</tt> 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     * <tt>IllegalArgumentException</tt>. 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     */
376    int drainTo(Collection<? super E> c, int maxElements);
377}
378