-1

Why I think ArrayBlockingQueue implementation doesn't make sense -

  1. A queue always adds at the end and removes from the front. Which means a linked list would be the most efficient data-structure to implement it.
  2. Queue items are never accessed using index so it defeats the purpose of having an indexed data-structure
  3. Arrays are always pre-allocated and difficult structures to increase/decrease in size
  4. Arrays require contiguous memory allocation which is not the use case of queues, it might trigger compaction cycle of GC to de-fragment heap
  5. Removal of the first element of an array would mean re-ordering rest of the indices, which is the most frequent use case of a Queue. Why to take this overhead ?

Does someone think otherwise ?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Bhushan
  • 2,256
  • 3
  • 22
  • 28

2 Answers2

4

Yes, the Javadoc states

This is a classic "bounded buffer", in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Once created, the capacity cannot be changed.

All you need is an index to the head and tail.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • That explains the indexing part. What do you think about the choice of the Data-structure. Wouldn't it be more efficient to use a LinkedList instead ? – Bhushan Jun 02 '14 at 05:42
  • 2
    @Bhushan Ok, so point 1 and 2 have been dispelled because of the indexing. Point 3 has been dispelled because an `ArrayBlockingQueue` is fixed size. For 4, that will probably very rarely happen in practice. What's more, a `LinkedList` implementation requires more objects to hold the nodes and more variables to reference the next and previous objects. For point 5 again we have the head and tail indices, so there is no re-ordering. – Sotirios Delimanolis Jun 02 '14 at 05:46
2

If you actually looked at the implementation, you would see that ArrayBlockingQueue uses an array as a ring buffer. This means that while it has a trivial effect on its operations, needing to do simple integer calculations, there's no need to reallocate or reorder anything, ever.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152