What is the ArrayBlockingQueue.offer() method in Java?

ArrayBlockingQueue is a bounded, thread-safe queue that uses a fixed-size array. This means that once the object is created, the size cannot be changed. The elements of this queue follow First-In-First-OutElements are inserted at the end of the queue and retrieved from the head of the queue. null objects are not allowed as elements.

The offer() method can be used to add an element to the end of the queue. The element will only be added if the queue is not full. Otherwise, the queue remains unchanged.

Syntax

public boolean offer(E e)

Parameter(s)

  • E e: This method takes the element e to be added to the queue as an argument.

Return value

  • boolean: offer() returns true if the element is successfully added to the queue. Otherwise, the method returns false.

Code

The code below demonstrates how to use the offer() method.

import java.util.concurrent.ArrayBlockingQueue;
class Offer {
public static void main( String args[] ) {
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
queue.offer("1");
queue.offer("2");
queue.offer("3");
queue.offer("4");
queue.offer("5");
System.out.println("The queue is " + queue);
System.out.println("Is element 6 added " + queue.offer("6"));
System.out.println("The queue is " + queue);
}
}

Code explanation

  • Line 1: Import ArrayBlockingQueue from the java.util.concurrent package.

  • Line 4: Create an object for the ArrayBlockingQueue class with the name queue and size 5.

  • Line 5 to 9: Use the offer method to add five elements to the queue object. In this state, the queue is full.

  • Line 11: Try adding a 6th element to the queue. The queue is already full, so the method returns false and the queue remains unchanged.

Free Resources