What is ArrayBlockingQueue.remainingCapacity() in Java?
Overview
ArrayBlockingQueueis a thread-safe and bounded queue. Internally,ArrayBlockingQueueuses a fixed-size array. Once the object is created, its size cannot be changed. The elements of theArrayBlockingQueuefollow First-In-First-Out (elements are inserted at the end of the queue and retrieved from the head of the queue).nullobjects 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.
Syntax
public int remainingCapacity()
Parameters
This method doesn’t take any parameters.
Return value
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.
Code
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());}}
Code explanation
In the code above:
-
We import the
ArrayBlockingQueuefrom thejava.util.concurrentpackage. -
We create an object for the
ArrayBlockingQueueclass with the namequeueand size5. -
We use the
add()method to add three elements to thequeueobject. -
We use the
remainingCapacity()method to get the remaining capacity of thequeue.