Multithreading
- Concurrency in Java: Reentrant, Read/Write and Stamped Locks
- Concurrency in Java: CompletableFuture and its use
- Concurrency in Java: Producer-consumer problem using BlockingQueue
- Concurrency in Java: Producer-Consumer Problem
- Concurrency in Java: Creating and Starting a Thread
- Concurrency in Java: Interrupting and Joining Threads
- Concurrency in Java: Race condition, critical section, and atomic operations
- Concurrency in Java: "synchronized" and "volatile" keywords
- Concurrency in Java: using wait(), notify() and notifyAll()
- Concurrency in Java: Thread pools, ExecutorService & Future
- Concurrency in Java: What is "Semaphore" and its use?
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 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.
Concurrency in Java: CompletableFuture and its use
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.