Concurrency in Java: Producer-consumer problem using BlockingQueue
- 4.7/5
- 4880
- Jul 20, 2024
The java.util.concurrent.BlockingQueue is a queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element and wait for space to become available in the queue when storing an element.
A BlockingQueue may be capacity-bound and does not accept null elements.
BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.
BlockingQueue methods
BlockingQueue methods come in four forms for handling operations that cannot be satisfied immediately but may be satisfied at some point in the future:
1) Throws exception
2) Special value (null or false)
3) Blocks
4) Times out
Throws exception | Special value | Blocks | Times out | |
---|---|---|---|---|
Insert | add(e) | offer(e) | put(e) | offer(e, time, unit) |
Remove | remove() | poll() | take() | poll(time, unit) |
Examine | element() | peek() | not applicable | not applicable |
Producer-Consumer using BlockingQueue
A BlockingQueue can be safely used with multiple producers and multiple consumers.
... ... Produced: Thread-1, RemainingCapacity: 3 Produced: Thread-1, RemainingCapacity: 8 Consumed: Thread-3, RemainingCapacity: 8 Consumed: Thread-2, RemainingCapacity: 8 Consumed: Thread-2, RemainingCapacity: 10 Produced: Thread-0, RemainingCapacity: 8 Produced: Thread-0, RemainingCapacity: 9 Produced: Thread-0, RemainingCapacity: 8 Consumed: Thread-2, RemainingCapacity: 9 Consumed: Thread-2, RemainingCapacity: 9 Consumed: Thread-2, RemainingCapacity: 10 Consumed: Thread-3, RemainingCapacity: 9 Produced: Thread-1, RemainingCapacity: 7 Produced: Thread-0, RemainingCapacity: 8 Produced: Thread-1, RemainingCapacity: 9 Produced: Thread-1, RemainingCapacity: 8 Produced: Thread-1, RemainingCapacity: 7 Produced: Thread-1, RemainingCapacity: 6 ... ...
To know more about Producer-Consumer Problem visit: Producer-Consumer Problem.