What is the ConcurrentLinkedDeque.offerFirst() method in Java?

The ConcurrentLinkedDeque is thread-safe unbounded deque. The null value is not permitted as an element. We can use the ConcurrentLinkedDeque when 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 ConcurrentLinkedDeque class.

  • In line 4, we create a ConcurrentLinkedDeque object with the name deque.

  • In line 5, we use the offerFirst method of the deque object to add an element ("1") as the first element of the deque. Then, we print it.

  • In line 8, we use the offerFirst method to add an element ("2") as the first element of the deque. Finally, we print it. Now, the deque is [2,1].

Free Resources