Queue ------------
1. ArrayDeque, (array dual-end Queue)
2. PriorityQueue, (priority queue)
3. ConcurrentLinkedQueue, (linked list-based Concurrent Queue)
4. DelayQueue (delayed blocking Queue) (blocking queue implements the BlockingQueue Interface)
5. ArrayBlockingQueue (array-Based Concurrent blocking Queue)
6. Queue blockingqueue (chain table-based FIFO blocking Queue)
7. Define blockingdeque, (based on the linked list of FIFO double-ended blocking queues)
8. PriorityBlockingQueue, (unbounded blocking queue with priority)
9. SynchronousQueue (concurrent synchronization blocking Queue)
-----------------------------------------------------
ArrayBlockingQueue Is a bounded blocking queue supported by arrays. This queue sorts the elements according to the FIFO principle. The queue header is the element with the longest time in the queue. The tail of a queue is the element with the shortest time in the queue. Insert the new element to the end of the queue. The queue acquisition operation obtains the element starting from the queue header.
This is a typical "bounded cache zone". fixed-size arrays keep the elements inserted by the producer and the elements extracted by the user. Once such a cache area is created, its capacity cannot be increased. An attempt to add an element to the full queue results in blocking operations. An attempt to extract an element from the empty queue results in similar blocking.
This class supports an optional fair policy for sorting the waiting producer thread and consumer thread. This sorting is not guaranteed by default. However, a queue constructed by setting the fairness (fairness) to true allows access to threads in FIFO order. Fairness usually reduces throughput, but also reduces variability and avoids "imbalance ".
Copy codeThe Code is as follows: public class ArrayBlockingQueue <E> extends AbstractQueue <E> implements BlockingQueue <E>, java. io. Serializable {
/** Queue element array */
Private final E [] items;
/** Index (take, poll, or remove operation) for retrieving and deleting elements )*/
Private int takeIndex;
/** Index (put, offer, or add operation) When an element is added )*/
Private int putIndex;
/** Number of queue elements */
Private int count;
/** Lock */
Private final ReentrantLock lock;
/** Conditions for obtaining an operation */
Private final Condition notEmpty;
/** Conditions for the insert operation */
Private final Condition notFull;
// When the length of the array is exceeded, reset it to 0.
Final int inc (int I ){
Return (++ I = items. length )? 0: I;
}
/**
* Insert an element (called only when the lock is obtained)
*/
Private void insert (E x ){
Items [putIndex] = x;
PutIndex = inc (putIndex );
++ Count;
NotEmpty. signal ();
}
/**
* Obtain and remove elements (called only when the lock is obtained)
*/
Private E extract (){
Final E [] items = this. items;
E x = items [takeIndex];
Items [takeIndex] = null;
TakeIndex = inc (takeIndex); // move to the next location
-- Count;
NotFull. signal ();
Return x;
}
/**
* Delete the I-position element.
*/
Void removeAt (int I ){
Final E [] items = this. items;
// If removing front item, just advance
If (I = takeIndex ){
Items [takeIndex] = null;
TakeIndex = inc (takeIndex );
} Else {
// Move all the elements after I until putIndex to a forward position
For (;;){
Int nexti = inc (I );
If (nexti! = PutIndex ){
Items [I] = items [nexti];
I = nexti;
} Else {
Items [I] = null;
PutIndex = I;
Break;
}
}
}
-- Count;
NotFull. signal ();
}
/**
* Constructor: Specify the capacity. Default policy (not in FIFO order)
*/
Public ArrayBlockingQueue (int capacity ){
This (capacity, false );
}
/**
* Constructor: Specify the capacity and policy
*/
Public ArrayBlockingQueue (int capacity, boolean fair ){
If (capacity <= 0)
Throw new IllegalArgumentException ();
This. items = (E []) new Object [capacity];
Lock = new ReentrantLock (fair );
NotEmpty = lock. newCondition ();
NotFull = lock. newCondition ();
}
/**
* Construct through a set
*/
Public ArrayBlockingQueue (int capacity, boolean fair,
Collection <? Extends E> c ){
This (capacity, fair );
If (capacity <c. size ())
Throw new IllegalArgumentException ();
For (Iterator <? Extends E> it = c. iterator (); it. hasNext ();)
Add (it. next ());
}
/**
* Insert an element to the end of the Team (super calls the offer method)
* Public boolean add (E e ){
* If (offer (e ))
* Return true;
* Else
* Throw new IllegalStateException ("Queue full ");
*}
* Insert the specified element to the end of the queue (if it is feasible immediately and does not exceed the capacity of the queue ),
* Returns true if the queue is successful. If the queue is full, an IllegalStateException is thrown.
*/
Public boolean add (E e ){
Return super. add (e );
}
/**
* Insert the specified element to the end of the queue (if it is feasible immediately and does not exceed the capacity of the queue ),
* True is returned when the queue is successful. If the queue is full, false is returned.
*/
Public boolean offer (E e ){
If (e = null) throw new NullPointerException ();
Final ReentrantLock lock = this. lock;
Lock. lock ();
Try {
If (count = items. length)
Return false;
Else {
Insert (e );
Return true;
}
} Finally {
Lock. unlock ();
}
}
/**
* Insert the specified element to the end of the queue. If the queue is full, wait for the available space.
*/
Public void put (E e) throws InterruptedException {
If (e = null) throw new NullPointerException ();
Final E [] items = this. items;
Final ReentrantLock lock = this. lock;
Lock. lockInterruptibly ();
Try {
Try {
While (count = items. length)
NotFull. await ();
} Catch (InterruptedException ie ){
NotFull. signal (); // propagate to non-interrupted thread
Throw ie;
}
Insert (e );
} Finally {
Lock. unlock ();
}
}
/**
* Insert the specified element to the end of the queue. If the queue is full, wait for the available space before reaching the specified waiting time.
*/
Public boolean offer (E e, long timeout, TimeUnit unit)
Throws InterruptedException {
If (e = null) throw new NullPointerException ();
Long nanos = unit. toNanos (timeout );
Final ReentrantLock lock = this. lock;
Lock. lockInterruptibly ();
Try {
For (;;){
If (count! = Items. length ){
Insert (e );
Return true;
}
If (nanos <= 0) // returns if the time reaches
Return false;
Try {
Nanos = notFull. awaitNanos (nanos );
} Catch (InterruptedException ie ){
NotFull. signal (); // propagate to non-interrupted thread
Throw ie;
}
}
} Finally {
Lock. unlock ();
}
}
// Obtain and remove the queue header. If the queue is empty, null is returned.
Public E poll (){
Final ReentrantLock lock = this. lock;
Lock. lock ();
Try {
If (count = 0)
Return null;
E x = extract ();
Return x;
} Finally {
Lock. unlock ();
}
}
// Obtain and remove the header of this queue and wait until the element becomes available (if necessary ).
Public E take () throws InterruptedException {
Final ReentrantLock lock = this. lock;
Lock. lockInterruptibly ();
Try {
Try {
While (count = 0)
NotEmpty. await ();
} Catch (InterruptedException ie ){
NotEmpty. signal (); // propagate to non-interrupted thread
Throw ie;
}
E x = extract ();
Return x;
} Finally {
Lock. unlock ();
}
}
// Obtain and remove the header of this queue and wait for the available elements before the specified wait time (if necessary ).
Public E poll (long timeout, TimeUnit unit) throws InterruptedException {
Long nanos = unit. toNanos (timeout );
Final ReentrantLock lock = this. lock;
Lock. lockInterruptibly ();
Try {
For (;;){
If (count! = 0 ){
E x = extract ();
Return x;
}
If (nanos <= 0)
Return null;
Try {
Nanos = notEmpty. awaitNanos (nanos );
} Catch (InterruptedException ie ){
NotEmpty. signal (); // propagate to non-interrupted thread
Throw ie;
}
}
} Finally {
Lock. unlock ();
}
}
// Obtain but not remove the header of this queue. If this queue is empty, null is returned.
Public E peek (){
Final ReentrantLock lock = this. lock;
Lock. lock ();
Try {
Return (count = 0 )? Null: items [takeIndex];
} Finally {
Lock. unlock ();
}
}
/**
* Returns the number of elements in the queue.
*/
Public int size (){
Final ReentrantLock lock = this. lock;
Lock. lock ();
Try {
Return count;
} Finally {
Lock. unlock ();
}
}
/**
* Returns the number of other elements that the queue can accept, ideally without blocking (no memory or resource constraints exist.
*/
Public int remainingCapacity (){
Final ReentrantLock lock = this. lock;
Lock. lock ();
Try {
Return items. length-count;
} Finally {
Lock. unlock ();
}
}
/**
* Remove a single instance of a specified element from this queue (if any ).
*/
Public boolean remove (Object o ){
If (o = null) return false;
Final E [] items = this. items;
Final ReentrantLock lock = this. lock;
Lock. lock ();
Try {
Int I = takeIndex;
Int k = 0;
For (;;){
If (k ++> = count)
Return false;
If (o. equals (items [I]) {
RemoveAt (I );
Return true;
}
I = inc (I );
}
} Finally {
Lock. unlock ();
}
}
/**
* If the queue contains the specified element, true is returned.
*/
Public boolean contains (Object o ){
If (o = null) return false;
Final E [] items = this. items;
Final ReentrantLock lock = this. lock;
Lock. lock ();
Try {
Int I = takeIndex;
Int k = 0;
While (k ++ <count ){
If (o. equals (items [I])
Return true;
I = inc (I );
}
Return false;
} Finally {
Lock. unlock ();
}
}
......
}
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.