So far I’ve written two articles on Producer Consumer concept on Crunchify. 1st one to explain Java Semaphore and Mutex and 2nd one to explain Concurrent Read/Write.
In this Java Tutorial we will go over same Producer/Consumer concept to explain the BlockingQueue in Java.
What are the advantages of Blocking Queue in Java?
A java.util.Queue 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.
We need to create four Java Classes:
CrunchifyMessage.java to put and get message
CrunchifyBlockingProducer.java to put message into queue
CrunchifyBlockingConsumer.java to get message from queue
CrunchifyBlockingMain.java to start test
BlockingQueue implementations are thread-safe. All queuing methods are atomic in nature and use internal locks.
Let’s get started on Thread-Safe BlockingQueue implementation in Java
Step-1
Create class CrunchifyMessage.java. This is simple Java Object.
Step-2
Create producer CrunchifyBlockingProducer.java which created simple msg and put it into queue.
Step-3
Create class CrunchifyBlockingConsumer.java which consumes message from queue.
Step-4
Create simple CrunchifyBlockingMain.java method which runs the BlockingQueue test. Run this program to check BlockingQueue behavior.
A BlockingQueue does not accept null elements. Implementations throw NullPointerException on attempts to add, put or offer a null.
A null is used as a sentinel value to indicate failure of poll operations.
Result:
When we should use java.util.concurrent.BlockingQueue?
When you want to throttle some sort of incoming request then you should use the same
A producers can get far ahead of the consumers with an unbounded queue. If consumer is not catching up with producer then it may cause an OutOfMemoryError. In situations like these, it may be better to signal a would-be producer that the queue is full, and to give up quickly with a failure.
In other words: the producers are naturally throttled.
Blocking Queue is normally used in concurrent application
It provides a correct, thread-safe implementation
Memory consumption should be limited as well
The post What is Thread-Safe BlockingQueue in Java? When should you use it? Implementation Attached appeared first on Crunchify.
More Related Articles For You...
Java: Producer Consumer Example – Handle Concurrent Read/Write
Java Thread State Introduction with Example – Life Cycle of a Thread
In Java How to Set and Get Thread Priority? Get Thread ID, Count, Class, StackTrace, ThreadGroup and More