In this tutorial, we will learn about BlockingQueue Interface and it's methods in Java.
BlockingQueue is considered as the thread-safe collection. It is because it can be helpful in multi-threading operations.Suppose one thread is inserting elements to the queue and another thread is removing elements from the queue.Now, if the first thread runs slower, then the blocking queue can make the second thread wait until the first thread completes its operation.
We can not create objects of an interface so we need derived-classes to create objects. So Java provided us 2 derived classes for our use.They are :
Some of the commonly used methods of the Queue interface are:
Methods | Description |
---|---|
add(E e) | Inserts the given element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success. |
contains(Object o) | Returns true if this queue contains the given element. |
drainTo(Collection c) | Removes all available elements from this queue and adds them to the given collection. |
drainTo(Collection c, int maxElements) | Removes at most the given number of available elements from this queue and adds them to the given collection. |
offer(E e) | Inserts the given element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success. |
offer(E e, long timeout, TimeUnit unit) | Inserts the given element into this queue, waiting up to the given wait time if necessary for space to become available.It reurns true if got success. |
poll(long timeout, TimeUnit unit) | Retrieves and removes the head of this queue, waiting up to the given wait time if necessary for an element to become available. |
put(E e) | Inserts the given element into this queue, waiting if necessary for space to become available. |
remainingCapacity() | Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking, or Integer.MAX_VALUE if there is no intrinsic limit. |
remove(Object o) | Removes a single instance of the given element from this queue, if it is present. |
take() | Retrieves and removes the head of this queue, waiting if necessary until an element becomes available. |