What is the ConcurrentLinkedDeque.offerFirst() method in Java?
The
ConcurrentLinkedDequeis thread-safe unbounded deque. Thenullvalue is not permitted as an element. We can use theConcurrentLinkedDequewhen multiple threads are sharing a single Deque.
The offerFirst method can be used to add an element as the head(first) element of the ConcurrentLinkedDeque object.
Syntax
public boolean offerFirst(E e)
Parameters
The offerFirst method takes the element to the Deque as a parameter. This method throws NullPointerException if the argument is null.
Return value
The offerFirst method returns true if the element is added to the Deque.
Code
The code below demonstrates how to use the offerFirst method:
import java.util.concurrent.ConcurrentLinkedDeque;class OfferFirst {public static void main( String args[] ) {ConcurrentLinkedDeque<String> deque = new ConcurrentLinkedDeque<>();deque.offerFirst("1");System.out.println("The deque is " + deque);deque.offerFirst("2");System.out.println("The deque is " + deque);}}
Explanation
In the code above,
-
In line 1, we import the
ConcurrentLinkedDequeclass. -
In line 4, we create a
ConcurrentLinkedDequeobject with the namedeque. -
In line 5, we use the
offerFirstmethod of thedequeobject to add an element ("1") as the first element of thedeque. Then, we print it. -
In line 8, we use the
offerFirstmethod to add an element ("2") as the first element of thedeque. Finally, we print it. Now, the deque is[2,1].