ArrayBlockingQueue
is a thread-safe and bounded queue. Internally,ArrayBlockingQueue
uses a fixed-size array. Once the object is created, its size cannot be changed. The elements of theArrayBlockingQueue
follow First-In-First-Out (elements are inserted at the end of the queue and retrieved from the head of the queue).null
objects are not allowed as elements in theArrayBlockingQueue
.
The remainingCapacity()
method is used to get the number of elements that can be accepted into the ArrayBlockingQueue
object without blocking.
public int remainingCapacity()
This method doesn’t take any parameters.
The remainingCapacity()
method returns an integer value that represents the remaining capacity.
Note: While using the
remainingCapacity()
method, we cannot ensure that the attempt to insert will succeed because there may be a chance that another thread is about to insert or remove an element.
The code below demonstrates how to use the remainingCapacity()
method.
import java.util.concurrent.ArrayBlockingQueue;class RemainingCapacity {public static void main( String args[] ) {ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(5);queue.add("1");queue.add("2");queue.add("3");System.out.println("The queue is " + queue);System.out.println("queue.remainingCapacity(): " + queue.remainingCapacity());}}
In the code above:
We import the ArrayBlockingQueue
from the java.util.concurrent
package.
We create an object for the ArrayBlockingQueue
class with the name queue
and size 5
.
We use the add()
method to add three elements to the queue
object.
We use the remainingCapacity()
method to get the remaining capacity of the queue
.