BlockingQueue and blockingqueue in java

Source: Internet
Author: User
Tags addall

BlockingQueue and blockingqueue in java

I. Overview

Located in java. util. concurrent and declared: public interfaceBlockingQueue <E>ExtendsQueue <E>

Supports two additional operationsQueueThe two operations are: Wait for the queue to become non-empty when getting the element, and wait for the space to become available when storing the element.

BlockingQueueThe method appears in four forms. for operations that cannot be met immediately but may be satisfied at a certain time point in the future, these four forms of processing are different: the first is to throw an exception, the second is to return a special value (NullOrFalseDepends on the Operation). The third is to block the current thread indefinitely before the operation is successful, and the fourth is to block the thread only within the given maximum time limit before giving up. The following table summarizes these methods:

  Throw an exception Special Value Blocking Timeout
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Check element() peek() Unavailable Unavailable
BlockingQueueNot accepted NullElement. Try Add, PutOr OfferOne NullSome implementations throw NullPointerException. NullUsed as an indication PollAlert value for operation failure.

BlockingQueueIt can be a limited capacity. It can haveRemainingCapacityBeyond this capacity, you will not be able to get anywherePutAdditional element. No internal capacity constraintsBlockingQueueAlways reportInteger. MAX_VALUE.

BlockingQueueThe implementation is mainly used for producer-user queues, but it also supportsCollectionInterface. For exampleRemove (x)It is possible to remove any element from the queue. However, this operation is usuallyNoIt can be executed effectively and can only be used occasionally in a planned manner, for example, when queuing information is canceled.

BlockingQueueImplementation is thread-safe. All queuing methods can use internal locks or other forms of concurrency control to automatically achieve their purpose. However,A large numberCollection operation (AddAll,ContainsAll,RetainAllAndRemoveAll)NoAutomatic execution is required unless otherwise specified. Therefore, for exampleCAfter some elements in,AddAll (c)It may fail (throwing an exception ).

BlockingQueueEssentiallyNoAny "close" or "shutdown" operation is supported to indicate that no items are added. The demand and use of such features are dependent on implementation. For example, a common strategy is to insert specialEnd-of-streamOrPoisonObjects.

The following is an example of a typical producer-user scenario. Note,BlockingQueueIt can be securely used with multiple producers and multiple users.

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) { ... handle ...}   }   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 other concurrent collections exist, put the objectBlockingQueueOperations in previous threadsHappen-beforeThenBlockingQueueTo access or remove the element.

This interface is a member of Java Collections Framework.

Ii. Method

1. booleanAdd(E)

Insert the specified element into this queue (if immediately feasible and does not violate the capacity limit), return if successful TrueIf no available space exists IllegalStateException. When using a queue with a capacity limit, it is usually preferred offer.

Specified:
Interface Collection<E>In add
Specified:
Interface Queue<E>In add
Parameters:
e-Elements to be added
Return Value:
True(According Collection.add(E))
Throw:
IllegalStateException-This element cannot be added due to capacity limit.
ClassCastException-If the class of the specified element cannot be added to this queue
NullPointerException-If the specified element is null
IllegalArgumentException-If some attributes of the specified element cannot be added to this queue
2. boolean Offer(E)
Insert the specified element into this queue (if immediately feasible and does not violate the capacity limit), return if successful TrueIf no available space exists, the system returns False. This method is usually better add(E)The latter may not be able to insert elements, but only throw an exception.

Specified:
Interface Queue<E>In offer
Parameters:
e-Elements to be added
Return Value:
If this element has been added to this queue, return TrueOtherwise False
Throw:
ClassCastException-If the class of the specified element cannot be added to this queue
NullPointerException-If the specified element is null
IllegalArgumentException-If some attributes of the specified element cannot be added to this queue
3. void Put(E) throwsInterruptedException inserts the specified element into this queue and waits for available space (if necessary ).

Parameters:
e-Elements to be added
Throw:
InterruptedException-If it is interrupted while waiting
ClassCastException-If the class of the specified element cannot be added to this queue
NullPointerException-If the specified element is null
IllegalArgumentException-If some attributes of the specified element cannot be added to this queue

4. boolean Offer(E e, long timeout, TimeUnit unit) throwsInterruptedException

Insert the specified element into the queue and wait for the available space before the specified wait time (if necessary ).

Parameters:
e-Elements to be added
timeout-The length of the waiting time before giving up, UnitTime Unit
unit-Determine how to explain TimeoutParameter TimeUnit
Return Value:
If yes, return TrueIf the specified wait time is exceeded before the available space False
Throw:
InterruptedException-If it is interrupted while waiting
ClassCastException-If the class of the specified element cannot be added to this queue
NullPointerException-If the specified element is null
IllegalArgumentException-If some attributes of the specified element cannot be added to this queue
5. E Take() ThrowsInterruptedException gets and removes the header of this queue, and waits until the element becomes available (if necessary ).

Return Value:
Header of this queue
Throw:
InterruptedException-If it is interrupted while waiting
6. E Poll(Long timeout, TimeUnit unit) throwsInterruptedException

Gets and removes the header of this queue and waits for available elements before the specified wait time (if necessary ).

Parameters:
timeout-The length of time to wait before giving up. Use UnitTime unit representation
unit-Determine how to explain TimeoutParameter TimeUnit
Return Value:
The header of this queue. If the specified wait time is exceeded before the element is available, the system returns Null
Throw:
InterruptedException-If it is interrupted while waiting
7. int RemainingCapacity()

Returns the number of additional elements that the queue can accept in an ideal situation without blocking (no memory or resource constraints exist). If there is no internal limit, returns Integer. MAX_VALUE.

Note,NoAlways pass the checkRemainingCapacityTo determine whether the element to be inserted is successful, because other threads are about to insert or remove an element.

Return Value:
Remaining capacity
8. boolean Remove(Object o)
Remove a single instance of the specified element from this queue (if any ). More specifically, if this queue contains one or more O. equals (e)Element ETo remove the element. If the queue contains the specified element (or the queue is changed due to a call ), True.

Specified:
Interface Collection<E>In remove
Parameters:
o-Elements to be removed from this queue (if any)
Return Value:
If the queue is changed due to a call, return True
Throw:
ClassCastException-If the class of the specified element is not compatible with this queue (optional)
NullPointerException-Optional if the specified element is null)
9. boolean Contains(Object o)
If the queue contains the specified element True. More specifically, when and only when this queue contains at least one O. equals (e)Element E, Return True.

Specified:
Interface Collection<E>In contains
Parameters:
o-Check whether objects in this queue are included
Return Value:
If the queue contains the specified element True
Throw:
ClassCastException-If the class of the specified element is not compatible with this queue (optional)
NullPointerException-Optional if the specified element is null)
10. int DrainTo(Collection <? SuperE> c)
Remove all available elements from the queue and add them to the given collection. This operation may be more effective than repeatedly polling this queue. In an attempt CWhen an element is not successfully added, the element may appear in two collections at the same time or in one of the collections, it may not appear in both collections. If you try to put a queue into your own queue IllegalArgumentExceptionException. In addition, if you modify the specified collection when you are performing this operation, the operation is not clear.

Parameters:
c-Collection of received transmission elements
Return Value:
Number of transfer elements
Throw:
UnsupportedOperationException-If the specified collection does not support adding elements
ClassCastException-If the class of this queue element cannot be added to the specified collection
NullPointerException-If the specified collection is null
IllegalArgumentException-If the specified collection is the queue, or some attributes of the queue element cannot be added to the specified collection
11. int DrainTo(Collection <? SuperE> c, int maxElements)
A maximum of available elements can be removed from this queue and added to the given collection. In an attempt CWhen an element is not successfully added, the element may appear in two collections at the same time or in one of the collections, it may not appear in both collections. If you try to put a queue into your own queue IllegalArgumentExceptionException. In addition, if you modify the specified collection when you are performing this operation, the operation is not clear.

Parameters:
c-Collection of received transmission elements
maxElements-Maximum number of transfer elements
Return Value:
Number of transfer elements
Throw:
UnsupportedOperationException-If the specified collection does not support adding elements
ClassCastException-If the class of this queue element cannot be added to the specified collection
NullPointerException-If the specified collection is null
IllegalArgumentException-If the specified collection is the queue, or some attributes of the queue element cannot be added to the specified collection








Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.