[英]How does ArrayBlockingQueue avoid shuffling array elements?
Scenario: My producer fills the array up, say capacity new int[10], before my consumer gets a chance to consume any. 场景:在我的消费者有机会消费之前,我的制作人填充了数组,比如容量new int [10]。 My producer sees the array is full and blocks.
我的制作人看到数组已满并阻塞。
Then my consumer comes along and removes int[0], and signals to the producer that the array now has an empty slot to fill. 然后我的消费者出现并删除int [0],并向生产者发出信号,表明该数组现在有一个空槽来填充。
My producer wakes up, and tries to add a new element to the array. 我的制作人醒来,并尝试向数组中添加一个新元素。 Considering only int[0] is free, and we are implementing FIFO, does ArrayBlockingQueue shuffle all the remaining 9 elements to the left, filling 0-8 indexes and leave int[9] free for the producer?
考虑到只有int [0]是免费的,我们正在实现FIFO,ArrayBlockingQueue是否将剩余的9个元素向左移动,填充0-8个索引并为生产者留下int [9]?
I've looked at the implementation but don't see any array copy functionality, 我查看了实现,但没有看到任何数组复制功能,
No copying of array elements is performed, because ArrayBlockingQueue
uses the array as a circular buffer. 不执行数组元素的复制,因为
ArrayBlockingQueue
将该数组用作循环缓冲区。 It maintaining two indexes, takeIndex
and putIndex
, and wraps them around when they reach the end of the array. 它维护两个索引,
takeIndex
和putIndex
,并在它们到达数组末尾时将它们包装起来。
After an operation that adds or takes an element it calls a private "increment" method called inc
, which wraps the index around the end: 在添加或获取元素的操作之后,它调用名为
inc
的私有“增量”方法,该方法将索引包装在末尾:
final int inc(int i) {
return (++i == items.length)? 0 : i;
}
Here is an example of how this method is used: 以下是如何使用此方法的示例:
private void insert(E x) {
items[putIndex] = x;
putIndex = inc(putIndex); // <<== Wraps around
++count;
notEmpty.signal();
}
ArrayBlockingQueue
maintain two variables suppose frontIndex and rearIndex to handle this instead of shifting elements. ArrayBlockingQueue
维护两个变量,假设frontIndex和rearIndex处理这个而不是移位元素。 If the queue is full. 如果队列已满。 and any element is pulled up by consumer from the index a[0] then the rearIndex moved to index 1 and next time whenever producer tries to add any element frontIndex will be moved to the 0 index after the 9 Index.
和任何元件由消费者从一个[0],则rearIndex移动到每当生产者试图增加任何元件frontIndex将在9索引之后被移动到0索引下一个时间索引1和索引拉起。 and the next put operation will be done on a[0] .
下一个put操作将在[0]上完成 。
Here FrontIndex==RearIndex means the queue is full. 这里FrontIndex == RearIndex表示队列已满。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.