ArrayBlockingQueue-How far can we go series (42), arrayblockingqueue

Source: Internet
Author: User

ArrayBlockingQueue-How far can we go series (42), arrayblockingqueue
How far can we go series (42)

Nonsense:

When you are free, read some juc source code to learn. Juc will be taken one side in the future. We will definitely come back later.

Subject:

What is BlockingQueue? java.util.QueueThat additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. blocking of a blocked queue during two operation Queues: 1. When an element in the queue is obtained and the queue is empty, it is blocked until there are elements in the queue. 2. When an element is stored, the queue is full and blocked until there is no available position in the queue. BlockingQueue is used as an interface to define implementation rules. The following are four types of queue core access operations:
  Throws exception Special value Blocks Times out
Insert add(e) offer(e) put(e) offer(e, time, unit)
Remove remove() poll() take() poll(time, unit)
Examine element() peek() Not applicable Not applicable
According to the above table, the policies when the queue is full or empty contain, throw an exception, return a boolean value, block the thread, and block the timeout. It is unclear why we should make such a choice. We need to note that, except for the third method, other methods do not actually block the thread. ArrayBlockingQueue:An array is used internally to implement a queue based on the first-in-first-out (FIFO) Principle of elements. After initialization, the queue capacity cannot be changed. Supports optional fairness mechanisms to ensure that blocked operation threads can be sorted in order. By default, this is an unfair mechanism. Source code implementation:1. Use an array of Object [] to store Elements
// The final Object [] items of the container in which the queue stores elements; // The int takeIndex of the next read or removal location; // The int putIndex of the next element; // Number of valid elements in the queue int count; // All access protection locks final ReentrantLock; // The Condition private final Condition notEmpty to be obtained; // private final Condition notFull;

2. There is a surround mechanism in the entire queue. For example, if I keep retrieving data at this time, the subscript read will always move back, knowing the end of the array. If at this time, the header of the array is specified at the end of the array. In this way, a queue is implemented. The implementation is very subtle. It can be said that it is the basic mechanism for implementing the entire queue.

In this way, the capacity of this queue cannot be changed.

// Move the Pointer Forward to final int inc (int I) {return (++ I = items. length )? 0: I;} // move the pointer back to final int dec (int I) {return (I = 0 )? Items. length: I)-1 ;}

3. Let's look at the implementation of the core put and take methods:

Put

Public void put (E) throws InterruptedException {checkNotNull (e); // null final ReentrantLock = this cannot be put. lock; // first assign the lock to the final modified local variable // In many JUC classes, you will see this syntax: assign a class attribute to the final variable in the method. // This is because the attributes of the class are stored in the heap, And the variables in the method are stored in the method stack, which is faster than accessing the method stack. // Here, the this. lock attribute needs to be accessed twice. by assigning a value to the local variable of the method, a heap access is saved. // Other class attributes do not need to be accessed once. Lock. lockInterruptibly (); // lock the try {// loop to avoid false wakeup. False wakeup means that if multiple threads are wait,
// When both are awakened, the following insert will be executed. // if the value is in the while loop, the system first determines the count size to determine whether to continue wait or insert. While (count = items. length) notFull. await (); // blocked thread insert (e);} finally {lock. unlock (); // release lock }}

Take

    public E take() throws InterruptedException {        final ReentrantLock lock = this.lock;        lock.lockInterruptibly();        try {            while (count == 0)                notEmpty.await();            return extract();        } finally {            lock.unlock();        }    }

The insert and extract methods are used. Of course, you can also see that these two methods are called only when the lock is held. Therefore, the call of this method does not need to be related to thread security, ensure thread security before calling:

Private void insert (E x) {items [putIndex] = x; // 1, save value, very simple putIndex = inc (putIndex); // 2, move subscript, use the inc method ++ count; // 3 to increase the total number of notEmpty elements. signal (); // 4, notifies the read thread waiting on non-null conditions}
Private E extract () {final Object [] items = this. items; // assign the class variable to the method variable first. We mentioned the usage E x = this. <E> cast (items [takeIndex]); items [takeIndex] = null; takeIndex = inc (takeIndex); -- count; notFull. signal (); return x ;}

 

Operation:

1. array of a ring

 

 

3. Obtain an element.

 

 

Of course, there are other methods in ArrayBlockingQueue, so I won't go into details here. If you are interested, you can continue your exploration.

 

Summary:

1. The Array Design of a ring is very clever.

2. encode the class variables to the method variables.

 

 

Let's move on

----------------------------------------------------------------------

Hard work may fail, but not hard work will certainly fail.

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.