![]() |
VOOZH | about |
The BlockingQueue interface in Java is a thread-safe queue from the java.util.concurrent package used in concurrent programming. It supports blocking operations, making it ideal for producer-consumer scenarios.
public interface BlockingQueue<E> extends Queue<E>
Here, E is the type of elements stored in the queue.
BlockingQueue: [1, 2, 3]
It extends the Queue interface and provides implementations like LinkedBlockingQueue and ArrayBlockingQueue.
There are two types of BlockingQueue.
Unbounded Queue is a queue that has no fixed capacity limit, allowing elements to be added indefinitely until system memory is exhausted.
BlockingQueue blockingQueue = new LinkedBlockingQueue();
Unbounded Queue: [10, 20, 30]
Bounded Queue is a queue with a fixed capacity that limits the number of elements it can hold at a time.
BlockingQueue blockingQueue = new LinkedBlockingDeque(5);
Bounded Queue: [1, 2, 3]
Elements can be added using add(), put(), or offer() methods.
BlockingQueue: [78, 35, 52, 74]
The elements of the LinkedBlockingDeque can be accessed using contains(), element(), peek(), poll().
Queue: [22, 125, 723, 172, 100] Queue contains 22 Head of queue: 22
Elements can be deleted from a LinkedBlockingDeque using remove(). Other methods such as take() and poll() can also be used in a way to remove the first and the last elements.
Before removing: [75, 86, 13, 44, 10] After removing: [75, 13, 10]
We can use an iterator to traverse the queue.
BlockingQueue elements: 166 246 66 292 98
| Method | Description |
|---|---|
| void put(E e) | Inserts the specified element, waiting if necessary for space to become available. |
| E take() | Retrieves and removes the head element, waiting if necessary until an element becomes available. |
| boolean offer(E e) | Inserts the specified element immediately, returning false if the queue is full. |
| boolean offer(E e, long timeout, TimeUnit unit) | Inserts the element, waiting up to the specified time for space. |
| E poll() | Retrieves and removes the head element immediately, or returns null if the queue is empty. |
| E poll(long timeout, TimeUnit unit) | Retrieves and removes the head element, waiting up to the specified time if empty. |
| E peek() | Retrieves, but does not remove, the head element, or returns null if empty. |
| boolean add(E e) | Inserts the specified element immediately, throwing an exception if the queue is full. |
| boolean remove(Object o) | Removes a specific element from the queue if present. |
| boolean contains(Object o) | Checks if the specified element exists in the queue. |
| int remainingCapacity() | Returns the number of additional elements the queue can accept without blocking. |
| boolean isEmpty() | Checks if the queue contains no elements. |
| Iterator<E> iterator() | Returns an iterator over the elements in the queue in proper sequence. |
| E element() | Retrieves, but does not remove, the head element; throws NoSuchElementException if empty. |