ArrayBlockingQueue remainingCapacity() Method in Java
Last Updated :
04 Apr, 2023
ArrayBlockingQueue is bounded, blocking queue that stores the elements internally backed by an array.
-
ArrayBlockingQueue class is a member of the Java Collections Framework.
-
Bounded means it will have a fixed size, you can not store number the elements more than the capacity of the queue.
-
The queue also follows FIFO (first-in-first-out) rule for storing and removing elements from the queue.
-
If you try to put an element into a full queue or to take an element from an empty queue then the queue will block you.
The remainingCapacity() method returns number of more elements that can be added to queue without blocking. This is always equal to difference between the initial capacity of this queue and the current size of this queue.
Syntax:
public int remainingCapacity()
Parameters: The method does not take any parameters.
Return Value: The method returns the remaining capacity of the queue.
Below programs illustrate remainingCapacity() method of ArrayBlockingQueue:
Program 1:
import java.util.concurrent.ArrayBlockingQueue;
public class GFG {
public static void main(String[] args)
{
int capacity = 5 ;
ArrayBlockingQueue<Integer> queue = new
ArrayBlockingQueue<Integer>(capacity);
queue.add( 23 );
queue.add( 32 );
System.out.println( "Queue :" + queue);
int remainingCapacity = queue.remainingCapacity();
System.out.println( "Remaining Capacity:" +
remainingCapacity);
queue.add( 54 );
queue.add( 78 );
System.out.println( "Queue :" + queue);
System.out.println( "Remaining Capacity:" +
queue.remainingCapacity());
}
}
|
Output:
Queue :[23, 32]
Remaining Capacity:3
Queue :[23, 32, 54, 78]
Remaining Capacity:1
Program 2:
import java.util.concurrent.ArrayBlockingQueue;
public class GFG {
public class User {
public String name;
public String age;
User(String name, String age)
{
this .name = name;
this .age = age;
}
}
public static void main(String[] args)
{
GFG gfg = new GFG();
gfg.RemainingCapacityExample();
}
public void RemainingCapacityExample()
{
int capacity = 5 ;
ArrayBlockingQueue<User> queue = new
ArrayBlockingQueue<User>(capacity);
User user1 = new User( "Aman" , "24" );
User user2 = new User( "Amar" , "23" );
User user3 = new User( "Sanjeet" , "25" );
queue.offer(user1);
queue.offer(user2);
queue.offer(user3);
int remainingCapacity = queue.remainingCapacity();
System.out.println( "Remaining Capacity:" +
remainingCapacity);
User user4 = new User( "Suvo" , "26" );
User user5 = new User( "Ravi" , "22" );
queue.offer(user2);
queue.offer(user3);
remainingCapacity = queue.remainingCapacity();
System.out.println( "Remaining Capacity:" +
remainingCapacity);
}
}
|
Output:
Remaining Capacity:2
Remaining Capacity:0
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ArrayBlockingQueue.html#remainingCapacity()
Share your thoughts in the comments
Please Login to comment...