Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

add
arrayblockingqueue
java
communitycreator

What is the ArrayBlockingQueue.add method in Java?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

An ArrayBlockingQueue is a bounded, thread-safe queue. Internally, it uses a fixed-size array. Once the object is created, the size cannot be changed. It also uses FIFO (First-In-First-Out) ordering. Elements are inserted at the end of the queue and retrieved from the head of the queue. Also, null objects are not allowed as elements.

The add method can be used to add an element to the end of the queue. The element will be added only if the queue is not full. Otherwise, an IllegalStateException will be thrown.

Syntax

public boolean add(E e)

Parameters

This method takes the element to be added to the queue as an argument.

Return value

This method returns true if the element is added to the queue successfully.

Code

The code below demonstrates how to use the add method.

import java.util.concurrent.ArrayBlockingQueue;
class Add {
public static void main( String args[] ) {
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
queue.add("1");
queue.add("2");
queue.add("3");
queue.add("4");
queue.add("5");
System.out.println("The queue is " + queue);
try{
queue.add("6");
}catch(Exception e) {
System.out.println("Exception on adding 6th element" + e);
}
}
}

Explanation

In the above code,

  • We imported the ArrayBlockingQueue from the java.util.concurrent package.

  • We created an object for the ArrayBlockingQueue class with the name queue and size 5.

  • We added five elements to the queue object, and now the queue is full.

  • We tried adding 6th element to the queue. The queue is already full, so an IllegalStateException is thrown.

RELATED TAGS

add
arrayblockingqueue
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring