Search code examples
javaqueueblockingqueue

Why ArrayBlockingQueue must have bound, while LinkedBlockingQueue not?


When I instantiate ArrayBlockingQueue, I must also put int capacity in its constructor. Same thing doesn't apply for LinkedBlockingQueue. I am interested in why is that?

Of course, I can also put bound in LinkedBlockingQueue, but it is optimal. Why is it optimal here, and not in ArrayBlockingQueue? Couldn't ArrayBlockingQueue have initial capacity on default like ArrayList has?


Solution

  • The documentation for ArrayBlockingQueue says.

    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. Attempts to put an element into a full queue will result in the operation blocking; attempts to take an element from an empty queue will similarly block.

    Since the capacity is fixed and can't change, it is up to the user of the class to decide when the queue should start to block.

    The documentation for LinkedBlockQueue says

    An optionally-bounded blocking queue based on linked nodes. This queue orders elements FIFO (first-in-first-out). The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. Linked queues typically have higher throughput than array-based queues but less predictable performance in most concurrent applications.

    The optional capacity bound constructor argument serves as a way to prevent excessive queue expansion. The capacity, if unspecified, is equal to Integer.MAX_VALUE. Linked nodes are dynamically created upon each insertion unless this would bring the queue above capacity.

    In this case, the blocked based on a supplied capacity. If specified, that blocking capacity is enforced the same as the ArrayBlockingQueue