The
ConcurrentLinkedQueue
is 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 theConcurrentLinkedQueue
when multiple threads are sharing a single Queue.
The offer
method can be used to add an element to the tail of the ConcurrentLinkedQueue
object.
public boolean offer(E e)
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.
The offer
method returns true
if the element is added to the queue.
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);}}
In the above code:
In line 1, we import the ConcurrentLinkedQueue
class.
In line 4, we create a ConcurrentLinkedQueue
object with the name queue
.
In line 5, we use the offer
method of the queue
object to add an element (1
) to the end of the queue
. Then, we print it.
In line 8, we use the offer
method to add an element (2
) to the end of the queue
. Finally, we print it.