javaqueueblockingqueuecapacity

Why Java API doesn't provide us with bounded Queue implementations for non-concurrent environment?


I am writing a small application and I want to have a bounded queue. The naive approach would be to do this:

Queue<Integer> queue = new ArrayDeque<> (5);

The problem with this is that I get initial capacity (which gets resized), and not max capacity. Doc for this constructor is:

 * Constructs an empty array deque with an initial capacity
 * sufficient to hold the specified number of elements.

Then I made a BlockingQueue that I know is 'blocking' and will fit the job, which I coded:

BlockingQueue<Integer> queue = new ArrayBlockingQueue<> (5);

I know this will work, as now I get a bounded queue. Doc for this constructor:

 * Creates an {@code ArrayBlockingQueue} with the given (fixed)
 * capacity and default access policy.

I thought the job is over, but I remembered that BlockingQueue implementations are thread-safe. And my application uses single thread. Thus I don't want to have a "performance hit".

Now I am kinda stuck. I want to use BlockingQueue's bounded constructor, but I don't want to have its synchronized overwhelm. What might be the best solution for this scenario? And how come are we not provided with a "plain" Queue that has bounds?


Solution

  • A single-threaded bounded queue implementation is not provided by the JDK likely because there is not a generic algorithm able to support all use cases. For example, what do you want to happen when the queue is full? Should incoming elements be discarded, should the last or first one?

    Implementing your own according to your needs should be trivial.