What is BlockingQueue?
BlockingQueue is a data structure to provide Queue like capability in multithreading environment.
what actually means when you say blocking?
It means that the if it is producer threads and the Queue is full already, it keeps waiting for the queue to be available, until interrupted. Same goes for consumer threads, it keeps waiting until an element is available to take unless it is interrupted.
Available blocking queues
- ArrayBlockingQueue
- LinkedBlockingQueue
- LinkedTransferQueue
- PriorityBlockingQueue
- SynchronousQueue
- DelayQueue
- LinkedBlockingDequeue
public static void main(String[] args) throws InterruptedException{
BlockingQueue<String> bq = new ArrayBlockingQueue<>(9);
Thread t1 = new Thread(() ->{
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
for(int i=0;i<11;i++){
try {
bq.put("Item-"+String.valueOf(i));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
Thread t2 = new Thread(() ->{
for(int i=0;i<11;i++){
try {
System.out.println(bq.take());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
t1.start(); t2.start();
t1.join();
t2.join();
}
In the above example t1 sleeps for 4s, so t2 will block as there will be no element present in the BlockingQueue initially. Once t1 crosses the threshold of 4s it enqueues the 'Item-1' and interrupts t2.
In contrast to above when the Queue is full it blocks until it to become available again so that it can push remaining 2 elements.
Several methods to perform Enqueue operation are
if the queue is full add will immediately throw an exception while put and offer keeps waiting.
boolean add(Element) -> IllegalStateException #Non Blocking
void put(Element) -> InterruptedException #blocking
boolean offer(Element) -> InterruptedException #blocking
Several methods to perform deque operation are
if the queue is empty all 3 methods will keep waiting for the element to become available until interrupted as all 3 are blocking in nature.
Element take() -> InterruptedException
Element poll() -> InterruptedException
Element poll(time, unit) -> InterruptedException
- method to remove an element from the queue if not present will return false.
boolean remove(element)
- These add the capability to remove all elements from the queue and add it to the collection provided in the argument.
int drainTo(targetCollection)
int drainTo(targetCollection, numberOfElementsToDrain)
Element peek()
Element element() -> exception
int size()
int remainingCapacity()
boolean contains(Element)