What is the ConcurrentLinkedQueue.offer() method in Java?
The
ConcurrentLinkedQueueis thread-safe unbounded queue. The elements are ordered by FIFO (First-In-First-Out). The elements are inserted at the tail (end) and retrieved from the head (start) of the queue. Null elements are not allowed as elements of the queue. We can use theConcurrentLinkedQueuewhen multiple threads are sharing a single Queue.
The offer method can be used to add an element to the tail of the ConcurrentLinkedQueue object.
Syntax
public boolean offer(E e)
Parameters
The offer method takes the element to be added to the ConcurrentLinkedQueue as a parameter. This method throws a NullPointerException if the argument is null.
Return value
The offer method returns true if the element is added to the queue.
Code
The code below demonstrates how to use the offer method.
import java.util.concurrent.ConcurrentLinkedQueue;class Offer {public static void main( String args[] ) {ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();queue.offer("1");System.out.println("The queue is " + queue);queue.offer("2");System.out.println("The queue is " + queue);}}
Explanation
In the above code:
-
In line 1, we import the
ConcurrentLinkedQueueclass. -
In line 4, we create a
ConcurrentLinkedQueueobject with the namequeue. -
In line 5, we use the
offermethod of thequeueobject to add an element (1) to the end of thequeue. Then, we print it. -
In line 8, we use the
offermethod to add an element (2) to the end of thequeue. Finally, we print it.