BlockingQueue Class
The BlockingQueue interface extends the Queue interface, and the classes that implement it are suitable for parallel programs where concurrency issues can arise. Among these, the most relevant ones are ArrayBlockingQueue, LinkedBlockingQueue, and PriorityBlockingQueue. All of them simulate a FIFO (queue) structure with thread-safe operations.
The difference lies in their underlying implementation: ArrayBlockingQueue is based on an array, LinkedBlockingQueue uses a linked list, and PriorityBlockingQueue allows you to specify a comparator during initialization to maintain a specific order of elements. None of these classes accept null elements, and you can specify a maximum capacity during initialization (which is mandatory for ArrayBlockingQueue).
The operations follow the FIFO principle (items are inserted at the end and removed from the beginning of the queue), as shown in the table below.
Operation | Throws Exception | Special Value | Blocks | Times Out |
---|---|---|---|---|
Insertion | add(e) | offer(e) | put(e) | offer(e, time, unit) |
Removal | remove() | poll() | take() | poll(time, unit) |
Examination | element() | peek() |
Although there are multiple methods for similar operations, their behavior differs. The most important distinction is whether they are blocking or not. For example, add(obj) adds an element only if there is space in the queue (i.e., if the maximum capacity has not been reached) and returns true if the operation succeeds, or throws an IllegalStateException otherwise. On the other hand, put(obj) blocks if there is not enough space in the queue and waits until it can successfully add the element.