Analysis and understanding of java synchronous package ArrayBlockingQueue class

Source: Internet
Author: User

Analysis and understanding of java synchronous package ArrayBlockingQueue class

Preface:

The ArrayBlockingQueue class is a blocking queue and is used as a condition for multi-threaded operations.


1. Official explanation

A blocking queue created on the array bound by BlockingQueue. The order of the queue elements is FIFO. The queue header is the longest element in the queue. The tail of the queue is the element with the shortest time in the queue. The new elements are inserted at the end of the queue, and the queue obtains the elements from the queue header.

This is a typical binding buffer in which an array of fixed sizes holds the data inserted by the producer and the consumer extracts the data. Once this class is created, the size of the array cannot be changed. If you try to use the put operation to insert an element to a full queue, this operation will be blocked; if you try to get an element from an empty queue, it will also be blocked.

This class recommends an optional fair strategy to sort the waiting producer and consumer threads. By default, this order is uncertain. However, the queue uses a fair set of true to allow threads to access the queue in the FIFO order. In general, fairness reduces throughput but reduces variability and avoids thread hunger.

This class and its Iterator implement all optional Collection methods based on the Iterator interface.


Ii. Source Code Analysis

Let's take a look at a special constructor code of the ArrayBlockingQueue class:

public ArrayBlockingQueue(int capacity, boolean fair) {        if (capacity <= 0)            throw new IllegalArgumentException();        this.items = new Object[capacity];        lock = new ReentrantLock(fair);        notEmpty = lock.newCondition();        notFull =  lock.newCondition();    }

In this constructor, the fair parameter is not noticed. It is the parameter passed to ReentrantLock, and this parameter is exactly the parameter that ReentrantLock determines whether it is a fair or unfair queue, for details about ReentrantLock, refer to my source code analysis and summary of the ReentrantLock class in java.

The two notEmpty and notFull parameters are actually Condition, while Condition can regard it as a blocking signal. The Condition subclass ConditionObject (which is the internal class of AbstractQueuedSynchronizer) there are two methods: signal and signalAll. The first method is to wake up the first thread in the queue, while signalAll is to wake up all the waiting threads in the queue, but only one waiting thread will be selected, these two methods can be seen as Variants of policy and policyall.

In the insert and remove methods of this blocking queue, signal is called to wake up the waiting thread. In the put method, if the queue is full, await is called, the insert method is called to insert an element until the queue has a blank space. The source code is as follows:

 public void put(E e) throws InterruptedException {        checkNotNull(e);        final ReentrantLock lock = this.lock;        lock.lockInterruptibly();        try {            while (count == items.length)                notFull.await();            insert(e);        } finally {            lock.unlock();        }    }

private void insert(E x) {        items[putIndex] = x;        putIndex = inc(putIndex);        ++count;        notEmpty.signal();    }

In fact, the programmer brother who designed this class has already thought that if we want to use this class, but we don't want to block the inserted elements after the queue is full, we provide the offer method, this offer method has a overload method. When the offer (E) method is called, if the queue is full, a false value is returned directly. If the queue is not full, insert is directly called and inserted into the queue. When the offer (E e, long timeout, TimeUnit unit) method is called, the queue will be blocked when the queue is full, however, the developer can set the timeout time here. If the queue is still full during the timeout, false is returned. The source code is as follows:

public boolean offer(E e, long timeout, TimeUnit unit)        throws InterruptedException {        checkNotNull(e);        long nanos = unit.toNanos(timeout);        final ReentrantLock lock = this.lock;        lock.lockInterruptibly();        try {            while (count == items.length) {                if (nanos <= 0)                    return false;                nanos = notFull.awaitNanos(nanos);            }            insert(e);            return true;        } finally {            lock.unlock();        }    }

public boolean offer(E e) {        checkNotNull(e);        final ReentrantLock lock = this.lock;        lock.lock();        try {            if (count == items.length)                return false;            else {                insert(e);                return true;            }        } finally {            lock.unlock();        }    }

Data insertion can be classified as blocking or non-blocking, so data extraction must also be classified as blocking or non-blocking.

The take method is a blocking method. When the queue is empty, it is blocked. The source code is as follows:

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

The poll method is an overloaded method. Compared with the offer method, it also has basic methods and timeout methods.

This class also provides the peek method to extract data, but the peek method extracts data from the right tail and the pool extracts data from the head of the queue, that is, the elements extracted by peek are the last elements in the queue, while those extracted by the pool are the elements that have the longest time in the queue.

Let's take a look at the iterator in this class. The iterator in this class is thread-safe. Why is thread-safe? Because lock is added to the next and remove methods implemented, the security cannot be stopped ~ Source code:

Private class Itr implements Iterator <E> {private int remaining; // Number of elements yet to be returned private int nextIndex; // Index of element to be returned by next private E nextItem; // Element to be returned by next call to next private E lastItem; // Element returned by last call to next private int lastRet; // Index of last element returned, or-1 if none Itr () {final ReentrantLock lo Ck = ArrayBlockingQueue. this. lock; lock. lock (); try {lastRet =-1; if (remaining = count)> 0) nextItem = itemAt (nextIndex = takeIndex);} finally {lock. unlock () ;}} public boolean hasNext () {return remaining> 0;} public E next () {final ReentrantLock lock = ArrayBlockingQueue. this. lock; lock. lock (); // lock try {if (remaining <= 0) throw new NoSuchElementException (); lastRet = nextIndex; E x = ItemAt (nextIndex); // check for fresher value if (x = null) {x = nextItem; // we are forced to report old value lastItem = null; // but ensure remove fails} else lastItem = x; while (-- remaining> 0 & // skip over nulls (nextItem = itemAt (nextIndex = inc (nextIndex ))) = null); return x;} finally {lock. unlock () ;}} public void remove () {final ReentrantLock lock = ArrayBlockingQueue. this. Lock; lock. lock (); try {int I = lastRet; if (I =-1) throw new IllegalStateException (); lastRet =-1; E x = lastItem; lastItem = null; // only remove if item still at index if (x! = Null & x = items [I]) {boolean removingHead = (I = takeIndex); removeAt (I); if (! RemovingHead) nextIndex = dec (nextIndex) ;}} finally {lock. unlock ();}}}



Iii. Summary

The description of this class has been analyzed by code. Next, let's summarize some features of this class:

1. Once created, the capacity cannot be changed

2. This class is thread-safe and the iterator is thread-safe.

3. The put and take methods of this class will be blocked after the queue is full and the queue is empty.

4. This class provides the offer and poll methods to insert and extract elements without blocking operations when the queue is full or the queue is empty.

5. The lock of this queue is unfair by default, that is, the order of the wake-up threads is uncertain.


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.