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 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 elementeto be added to the queue as an argument.
Return value
boolean:offer()returnstrueif the element is successfully added to the queue. Otherwise, the method returnsfalse.
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
ArrayBlockingQueuefrom thejava.util.concurrentpackage. -
Line 4: Create an object for the
ArrayBlockingQueueclass with the namequeueand size 5. -
Line 5 to 9: Use the
offermethod to add five elements to thequeueobject. 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
falseand the queue remains unchanged.