Home Post Multithreading

Concurrency in Java: Producer-consumer problem using BlockingQueue

Mar 31, 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 exceptionSpecial valueBlocksTimes out
Insertadd(e)offer(e)put(e)offer(e, time, unit)
Removeremove()poll()take()poll(time, unit)
Examineelement()peek()not applicablenot 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.

avatar

NK Chauhan

NK Chauhan is a Principal Software Engineer with one of the biggest E Commerce company in the World.

Chauhan has around 12 Yrs of experience with a focus on JVM based technologies and Big Data.

His hobbies include playing Cricket, Video Games and hanging with friends.

Categories
Spring Framework
Microservices
BigData
Core Java
Java Concurrency