ArrayBlockingQueue add() method in Java
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 add (E e) method inserts the element passed as a parameter to the method at the tail of this queue. If adding the element exceeds the capacity of the queue then the method will throw an IllegalStateException. This method returns true if adding of element is successful else it will throw an IllegalStateException.
public boolean add(E e)
e – the element to be added to queue.
true if adding is successful.
IllegalStateException – if this queue is full
NullPointerException – if the specified element is null
Below program illustrate adding element to ArrayBlockingQueue.
Output : After adding 23  After adding 32, 45, 12 [23, 32, 45, 12] After adding 27, 67 [23, 32, 45, 12, 27, 67]
Below program illustrate adding Element to ArrayBlockingQueue and exception thrown if queue is full.
Output : After adding all 5 elements to queue [23, 32, 45, 12, 27] Queue is full java.lang.IllegalStateException: Queue full at java.util.AbstractQueue.add(Unknown Source) at java.util.concurrent.ArrayBlockingQueue.add(Unknown Source) at defaultpackage.GFG.main(GFG.java:38)