What is the ConcurrentLinkedDeque.pollFirst() method in Java?
ConcurrentLinkedDequeis a thread-safe, unbounded deque. Thenullvalue is not permitted as an element. We can use theConcurrentLinkedDequewhen multiple threads share a single deque.
The pollFirst() method gets and removes the first element of the ConcurrentLinkedDeque object.
Syntax
public E pollFirst()
Parameters
This method doesn’t take any parameters.
Return value
The pollFirst() method retrieves and removes the first element of the deque object. If the deque object is empty, then the method returns null.
This method is similar to the
removeFirst()method, except that theremoveFirst()method throws theNoSuchElementExceptionif thedequeis empty, whereas thepollFirstmethod returnsnull.
Code
The code below demonstrates the use of the pollFirst() method.
import java.util.concurrent.ConcurrentLinkedDeque;class PollFirst {public static void main( String args[] ) {ConcurrentLinkedDeque<String> deque = new ConcurrentLinkedDeque<>();deque.add("1");deque.add("2");deque.add("3");System.out.println("The deque is " + deque);System.out.println("deque.pollFirst() returns : " + deque.pollFirst());System.out.println("The deque is " + deque);}}
Explanation
In the code above:
-
In line
1: We import theConcurrentLinkedDequeclass. -
In line
4: We create aConcurrentLinkedDequeobject nameddeque. -
In lines
5-7: We use thedequeobject to add three elements("1","2","3")todeque. -
In line
10: We use thepollFirst()method of thedequeobject to get and remove the first element. In our case,1will be removed and returned.