How does ArrayBlockingQueue avoid shuffling array elements?

Scenario: My producer fills an array, say, the capacity of new int [10], before my consumer gets a chance to consume any. My manufacturer sees that the array is full and blocked.

Then my consumer comes and removes int [0] and signals to the manufacturer that the array now has an empty slot to fill.

My producer wakes up and tries to add a new element to the array. Given that only int [0] is free, and we implement FIFO, does ArrayBlockingQueue shuffle the remaining 9 elements to the left, filling in 0-8 indices and leaving int [9] free for the manufacturer?

I looked at the implementation, but do not see the copy function of the array,

+6
source share
2 answers

Copying the elements of the array is not performed, since ArrayBlockingQueue uses the array as a circular buffer. It supports two indexes, takeIndex and putIndex , and wraps them when they reach the end of the array.

After an operation that adds or receives an element, it calls a private "increment" method called inc , which wraps the index around the end:

 final int inc(int i) { return (++i == items.length)? 0 : i; } 

Here is an example using this method:

 private void insert(E x) { items[putIndex] = x; putIndex = inc(putIndex); // <<== Wraps around ++count; notEmpty.signal(); } 
+5
source

ArrayBlockingQueue support two variables, setting frontIndex and rearIndex to handle this, rather than moving elements. If the queue is full. and any element is pulled by the consumer at index a [0] , then rearIndex moved to index 1 and the next time the manufacturer tries to add any frontIndex element will be moved to index 0 after index 9 . and the next input operation will be performed on a [0] .

Here FrontIndex == RearIndex means that the queue is full.

0
source

Source: https://habr.com/ru/post/1012215/


All Articles