I. Overview
Under Java.util.concurrent, Declaration: PublicInterfaceblockingqueue<e> extendsQueue <E>
Supports two additional operations, both of Queue
which wait for the queue to become non-empty when the element is fetched, and wait for space to become available when the element is stored.
The blockingqueue method appears in four forms, for operations that cannot be met immediately but may be satisfied at some point in the future, and these four forms are handled differently: the first is to throw an exception, and the second is to return a special value (null or false, depending on the operation), the third is to block the current thread indefinitely until the operation succeeds, and the fourth is to block only within the given maximum time limit before discarding. These methods are summarized in the following table:
|
Throw exception |
Special values |
Blocking |
Timeout |
Insert |
add(e) |
offer(e) |
put(e) |
offer(e, time, unit) |
Removed from |
remove() |
poll() |
take() |
poll(time, unit) |
Check |
element() |
peek() |
Not available |
Not available |
BlockingqueueDo not acceptNULLElements. TriedAdd、putOr OfferOneNULLelement, some implementations throwNullPointerException。NULLbe used as an indicationPollThe alert value of the operation failure.
The blockingqueue can be of limited capacity. It can have a remainingcapacityat any given time, exceeding this capacity, and cannot put additional elements without blocking. Blockingqueue that do not have any internal capacity constraints always report the remaining capacity of the Integer.max_value .
The Blockingqueue implementation is primarily used by the producer-consumer queue, but it also supports Collection
interfaces. So, for example, it is possible to use remove (x) to remove any element from the queue. However, this operation is usually not performed effectively and can only be used on a scheduled occasion, such as when the queued information is canceled.
blockingqueue implementations are thread-safe. All queueing methods can use internal locks or other forms of concurrency control to automatically achieve their purpose. However, a large number of Collection operations (addall,containsall,retainall , and removeall) are not automatic execution is necessary unless specifically stated in the implementation. So, for example,AddAll (c) might fail (throw an exception) after adding only some of the elements in C .
Blockingqueue Essentially does not support the use of any one of the "close" or "shutdown" actions to indicate that no more items are added. The need for and use of this functionality has a tendency to rely on implementation. For example, a common strategy is to insert special End-of-stream or poison objects for the producer, and interpret them based on the time the consumer obtains them.
The following is a use case based on a typical producer-consumer scenario. Note thatBlockingqueue can be safely used with multiple producers and multiple consumers.
Class Producer implements Runnable { private final blockingqueue queue; Producer (Blockingqueue q) {queue = q;} public void Run () { try { while (true) {queue.put (Produce ())} } catch (Interruptedexception ex) {... handle ...} } Object Produce () {...}} Class Consumer implements Runnable { private final blockingqueue queue; Consumer (Blockingqueue q) {queue = q;} public void Run () { try { while (true) {consume (Queue.take ())} } catch (Interruptedexception ex) {... ha Ndle ...} } void consume (Object x) {...}} Class Setup { void main () { Blockingqueue q = new somequeueimplementation (); Producer p = new Producer (q); Consumer C1 = new Consumer (q); Consumer C2 = new Consumer (q); New Thread (P). Start (); New Thread (C1). Start (); New Thread (C2). Start (); } }
Memory consistency Effect: when there are other concurrent collection, the action of putting the object BlockingQueue
in the previous thread Happen-before then BlockingQueue
accessing or removing the element from the other threads.
This interface is a member of the Java collections Framework.
Second, the method
1. Boolean Add (e )
-
-
inserts the specified element into this queue (if it is feasible immediately and does not violate the capacity limit), returns trueon success, and throws illegalstateexceptionif no space is currently available. Typically preferred when using a capacity-constrained queue
offer
.
-
-
-
Designated by:
-
Collection<E>
in the interface.
add
-
Designated by:
-
Queue<E>
in the interface
add
.
-
-
-
Parameters:
-
e
-the element to be added
-
Return:
- true(according to
Collection.add(E)
the provisions)
-
Thrown:
-
IllegalStateException
-If the element cannot be added due to a capacity limitation at this time
-
ClassCastException
-If the class of the specified element does not allow it to be added to this queue
-
NullPointerException
-If the specified element is null
-
IllegalArgumentException
-If certain attributes of the specified element are not allowed to be added to this queue
2.Boolean
Offer(Ee)
-
Inserts the specified element into this queue (if it is feasible immediately and does not violate the capacity limit), returns trueon success, or falseif no space is currently available. This method is generally preferable when using a capacity-constrained queue,
add(E)
which may not be able to insert elements, but only throws an exception.
-
-
Designated by:
-
Queue<E>
in the interface.
offer
-
-
Parameters:
-
e
-the element to be added
-
Return:
-
Returns trueif the element was added to this queue, otherwise false
-
Thrown:
-
ClassCastException
-If the class of the specified element does not allow it to be added to this queue
-
NullPointerException
-If the specified element is null
-
IllegalArgumentException
-If certain attributes of the specified element are not allowed to be added to this queue
3.void
put(Ee)throwsInterruptedexceptioninserts the specified element into this queue, waiting for the available space, if necessary.
-
-
-
-
Parameters:
-
e
-the element to be added
-
Thrown:
-If you
-
InterruptedException
are interrupted while waiting
-
ClassCastException
-If the class of the specified element does not allow it to be added to this queue
-
NullPointerException
-If the specified element is null
- -If certain properties of the specified element are not allowed to be added to this queue
4.Boolean
Offer(EE,Long Timeout, Timeunitunit)throwsInterruptedexception
-
Inserts the specified element into this queue, waiting for the available space (if necessary) before reaching the specified wait time.
-
-
-
Parameters:
-
e
-The element to be added
-
timeout
-The length of time to discard before waiting, in unit for time units
-
unit
-Determine how ti is interpreted timeunit of the meout parameter
-
Return:
-
Returns trueif successful, or false if the specified wait time is exceeded before space is available
-
Thrown:
-If you
-
InterruptedException
are interrupted while waiting
-
ClassCastException
-If the class of the specified element does not allow it to be added to this queue
-
NullPointerException
-If the specified element is null
- -If certain properties of the specified element are not allowed to be added to this queue
5, E
Take() throwsInterruptedexception gets and removes the head of this queue and waits (if necessary) until the element becomes available.
-
Return:
-
The head of this queue
-
Thrown:
-
InterruptedException
-If you are interrupted while waiting
6, E
Poll(long timeout, Timeunitunit)throwsInterruptedexception
-
gets and removes the header of this queue, waiting for the available elements (if necessary) before the specified wait time.
-
-
-
Parameters:
-
timeout
-The length of time to wait before discarding, expressed in unit time units
-
unit
-determines how the timeunit of the timeout parameter is interpreted
-
Return:
-
The head of this queue; returns NULL if the specified wait time is exceeded before the element is available
-
Thrown:
-
InterruptedException
-If you are interrupted while waiting
7.int
remainingcapacity()
returns the number of additional elements this queue can accept in an ideal case without blocking (no memory or resource constraints), or integer.max_valueif there is no internal limit.
Note that it is not always possible to check the remainingcapacity to see if an attempt to insert an element succeeds, as this can happen: Another thread is about to insert or remove an element.
-
Return:
-
remaining capacity
8. Boolean
remove (Object o)
removes a single instance of the specified element, if any, from this queue. More specifically, if this queue contains one or more element ethat satisfies o.equals (e) , the element is removed. Returns trueif this queue contains the specified element (or if the queue has been changed due to a call).
-
Designated by:
-
Collection<E>
in the interface
remove
.
-
Parameters:
-
o
-the element to remove from this queue (if present)
-
Return:
-
Returns true if this queue has changed because of a call
-
Thrown:
-
ClassCastException
-If the class of the specified element is incompatible with this queue (optional)
-
NullPointerException
-If the specified element is null (optional)
9, boolean contains (Object o)
returns trueif this queue contains the specified element. More precisely, returns truewhen and only if this queue contains at least one element e that satisfies o.equals (e) .
-
Designated by:
-
Collection<E>
in the interface
contains
.
-
Parameters:
-
o
-Check whether the objects in this queue are included
-
Return:
-
Returns true if this queue contains the specified element
-
Thrown:
-
ClassCastException
-If the class of the specified element is incompatible with this queue (optional)
-
NullPointerException
-If the specified element is null (optional)
10, int
Dr Ainto (Collection <? superE > C)
Removes all the elements that are available in this queue and adds them to the given collection. This operation may be more efficient than polling this queue repeatedly. When attempting to add an element to collection C is unsuccessful, it may cause the element to appear in two collection at the same time when the associated exception is thrown, or in one of the collection, or it may not be in two collection Appear. Attempting to put a queue in its own queue can cause a illegalargumentexception exception. In addition, if the specified collection is modified while this operation is in progress, the behavior of this operation is indeterminate.
-
Parameters:
-
c
-Receive the collection of the transmission element
-
Return:
-
Number of transport elements
-
Thrown:
-If the
-
UnsupportedOperationException
specified collection does not support adding elements
-
ClassCastException
-If the class for this queue element does not allow it to be added to the specified collection
-
NullPointerException
-if the specified Collec tion is null
-
IllegalArgumentException
-If the specified collection is this queue, or some properties of this queue element do not allow it to be added to the specified collection
11. int
Drainto (Collection <? SuperE > C, int maxelements)
removes a given number of available elements from this queue at most, and adds them to the given collection. When attempting to add an element to collection C is unsuccessful, it may cause the element to appear in two collection at the same time when the associated exception is thrown, or in one of the collection, or it may not be in two collection Appear. Attempting to put a queue in its own queue can cause a illegalargumentexception exception. In addition, if the specified collection is modified while this operation is in progress, the behavior of this operation is indeterminate.
-
Parameters:
-
c
-Receive the collection of the transport element
-
maxElements
-The maximum number of transport elements
-
Return:
-
Number of transport elements
-
Thrown:
-If the
-
UnsupportedOperationException
specified collection does not support adding elements
-
ClassCastException
-If the class for this queue element does not allow it to be added to the specified collection
-
NullPointerException
-if the specified coll Ection is null
-
IllegalArgumentException
-If the specified collection is this queue, or some properties of this queue element do not allow it to be added to the specified collection
Blocking queue Blockingqueue in Java