简体   繁体   中英

Why does ArrayBlockingQueue use arrays for interior buffer removal?

ArrayBlockingQueue contains a buffer as an array. It also supports the admittedly inefficient

public boolean remove(Object o)

Removal of interior elements in circular array based queues is an intrinsically slow and disruptive operation, so should be undertaken only in exceptional circumstances, ideally only when the queue is known not to be accessible by other threads.

Why did the designers use an array over a LinkedList here if I'm told LinkedLists are faster for removing elements from the middle of an array. Here is my theory:

Removals are mostly done from the Head, and maybe even tail, but rarely the middle. So the designers wanted to handle the more common use case and make that faster, therefore accepting the performance hit on the less common mid-buffer removal use case.

It's all in the name: the ArrayBlockingQueue uses an array as buffer, a LinkedBlockingQueue uses a linked list.

There are some implementation differences:

The ArrayBlockingQueue uses a fixed size array to build a ring buffer to store the elements, it has therefore a fixed size that cannot change (but also a fixed memory overhead).

The LinkedBlockingQueue uses a linked list, so can basically grow as necessary, but has to do memory allocation on adding elements.

On the less common remove(Object) call both of them have to scan for the object (and have therefore O(n) time complexity).

ArrayBlockingQueue uses an array because... well... it's an Array BlockingQueue, not a LinkedBlockingQueue.

If you want a linked-list implementation then use LinkedBlockingQueue .

Apart from that, you already have the answer: people very rarely want to remove something from the middle of a queue, so if you never do that, you can get the other advantages of the circular array implementation. If this is not suitable for your application then use a different implementation of BlockingQueue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM