Arrayblockingqueue application Analysis of Java set frame _java

Source: Internet
Author: User
Tags array length int size sorts
Queue
------------
1.ArrayDeque, (array two-terminal queue)
2.PriorityQueue, (priority queue)
3.ConcurrentLinkedQueue, (concurrent queues based on linked lists)
4.DelayQueue, (deferred blocking queue) (the blocking queue implements the Blockingqueue interface)
5.ArrayBlockingQueue, (concurrency blocking queue based on array)
6.LinkedBlockingQueue, (FIFO blocking queue based on linked list)
7.LinkedBlockingDeque, (based on the list of FIFO two-terminal blocking queue)
8.PriorityBlockingQueue, (unbounded blocking queue with priority)
9.SynchronousQueue (concurrent synchronous blocking queue)
-----------------------------------------------------
Arrayblockingqueue
is a bounded blocking queue supported by an array. This queue sorts the elements according to the FIFO (first-in first out) principle. The head of the queue is the element that has the longest time in the queue. The tail of the queue is the element that has the shortest time in the queue. The new element is inserted at the end of the queue, and the queue fetch operation starts from the queue header to obtain the element.
This is a typical "bounded buffer" with fixed-size arrays in which the producer inserts elements and the user extracts the elements. Once you create such a buffer, you can no longer increase its capacity. Attempting to put an element into a full queue causes the operation to be blocked, and attempting to extract elements from an empty queue causes a similar blockage.
This class supports an optional fair policy that sorts waiting producer threads and consumer threads. By default, this sort is not guaranteed. However, queues constructed by setting the fairness (fairness) to true allow the thread to be accessed in FIFO order. Fairness generally lowers throughput, but also reduces variability and avoids "imbalances."
Copy Code code as follows:

public class Arrayblockingqueue<e> extends abstractqueue<e> implements Blockingqueue<e>, java.io.Serializable {
/** Queue Element Array */
Private final e[] items;
/** the index (take, poll, or remove operation) when the element is fetched or deleted.
private int takeindex;
/** index when adding elements (put, offer or add operation) * *
private int putindex;
Number of/** queue elements * *
private int count;
/** Lock * *
Private final reentrantlock lock;
/** to obtain the operation conditions * *
Private final Condition Notempty;
/** the condition of the insert operation * *
Private final Condition Notfull;
When the array length is exceeded, reset to 0
Final INT Inc (int i) {
return (++i = = items.length)? 0:I;
}
/**
* Insert Element (called when Lock is acquired)
*/
private void Insert (E x) {
Items[putindex] = x;
Putindex = Inc (PUTINDEX);
++count;
Notempty.signal ();
}
/**
* Get and remove elements (invoked only if locks are acquired)
*/
Private E Extract () {
Final e[] items = this.items;
E x = Items[takeindex];
Items[takeindex] = null;
Takeindex = Inc (TAKEINDEX);//move to the next position
--count;
Notfull.signal ();
return x;
}
/**
* Delete element of I position
*/
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 the elements that are behind me up to the putindex one 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 ();
}
/**
* Construction method, specifying capacity, default policy (not accessed in FIFO order)
*/
public arrayblockingqueue (int capacity) {
This (capacity, false);
}
/**
* Construction method, specifying capacity and strategy
*/
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 ();
}
/**
* Constructed by Collection
*/
public arrayblockingqueue (int capacity, Boolean fair,
collection<? Extends e> c) {
This (capacity, fair);
if (Capacity < c.size ())
throw new IllegalArgumentException ();
for (ITERATOR&LT; extends e> it = C.iterator (); It.hasnext ();)
Add (It.next ());
}
/**
* Insert element to Team tail (super Invoke offer method)
* Public boolean Add (E e) {
* IF (offer (e))
* return true;
* Else
* Throw new IllegalStateException ("Queue full");
* }
* Inserts the specified element at the end of this queue (if it is immediately feasible and does not exceed the capacity of the queue),
* Returns true on success and throws IllegalStateException if the queue is full.
*/
Public boolean Add (E e) {
Return Super.add (e);
}
/**
* Inserts the specified element at the end of this queue (if it is immediately feasible and does not exceed the capacity of the queue),
* Returns true on success, False if this queue is full.
*/
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 ();
}
}
/**
* Inserts the specified element at the end of this queue and waits for available space if the queue is full.
*/
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 ();
}
}
/**
* Inserts the specified element at the end of this queue, and waits for the available space before the specified wait time if the queue is full.
*/
Public Boolean offer (e E, long timeout, timeunit)
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)//If time is up, return
return false;
try {
Nanos = Notfull.awaitnanos (Nanos);
catch (Interruptedexception IE) {
Notfull.signal (); Propagate to non-interrupted thread
throw ie;
}
}
finally {
Lock.unlock ();
}
}
Gets and removes the header of this queue, and returns null if the queue is empty.
Public E poll () {
Final Reentrantlock lock = This.lock;
Lock.lock ();
try {
if (count = = 0)
return null;
E x = extract ();
return x;
finally {
Lock.unlock ();
}
}
Gets and removes the header of this queue and waits (if necessary) before the element becomes available.
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 ();
}
}
Gets and removes the head of this queue and waits for the available elements (if necessary) before the specified wait time.
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 ();
}
}
Gets but does not remove the header of this queue, or returns null if the queue is empty.
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 this queue.
*/
public int size () {
Final Reentrantlock lock = This.lock;
Lock.lock ();
try {
return count;
finally {
Lock.unlock ();
}
}
/**
* Returns the number of other elements that this queue can accept without blocking ideally (no memory or resource constraints exist).
*/
public int remainingcapacity () {
Final Reentrantlock lock = This.lock;
Lock.lock ();
try {
return items.length-count;
finally {
Lock.unlock ();
}
}
/**
* Removes a single instance of the specified element from this queue, if one exists.
*/
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 ();
}
}
/**
* Returns True if the queue contains the specified element.
*/
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 ();
}
}
......
}
Related Article

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.