BlockingQueue Collection is a type of Java Queue. BlockingQueue is part of Java concurrent util package. It is best used in multi threading and producer-consumer scenarios. While adding an element to a a BlockingQueue, if there is no space it can wait till it becomes available. Similarly while retrieving, it will wait till an element is available if it is empty.
|Throws exception||Returns value||Blocks||Timed|
|Insert||add(e)||offer(e)||put(e)||offer(e, time, unit)|
|Examine||element()||peek()||not applicable||not applicable|
There are four types of methods available for each operations like insert, remove and examine in a BlockingQueue. The respective type of method has to be chosen according to our use case requirement.
- Throws exception – when an insert is performed if there is no space an exception is thrown.
- Returns value – returns a value like true or false. false means insufficient space and true means successful insertion
- Blocks – blocks the thread till the space is available
- Timed – waits for the specified amount of time
These methods are used in a multi-threaded scenario. BlockingQueue extends the Collection interface and so an implementation of a BlockingQueue will contain the standard collection methods as well. For example removing an element can be done using remove(index). BlockingQueue is always best used in a threaded scenario.
All these methods are guaranteed to be thread-safe. Other standard methods that are part of the collection may or may not be thread-safe and the choice is left to the implementation.
BlockingQueue Implementation in JDK
BlockingQueue is an interface. Either we should go for custom implementation or choose the existing implementations from the Java JDK. Following the different implementations available for the BlockingQueue in Java.
Following posts will have examples on implementing BlockingQueue using the above JDK BlockingQueue implementations and a custom implementation for BlockingQueue as well.
This Java tutorial was added on 29/09/2014.