What is the ArrayBlockingQueue.poll method in Java?

ArrayBlockingQueue is a bounded queue, and it is thread-safe. Internally it uses a fixed-size array. Once the object is created, the size cannot be changed. The elements of this queue follow First-In-First-Out(Elements are inserted at the end of the queue and retrieved from the head of the queue ). Also, null objects are not allowed as elements.

The poll method can be used to get and remove the head(first element) element of the ArrayBlockingQueue object.

Syntax

public E poll()

Parameters

This method doesn’t take any argument.

Return value

This method returns the head element of the queue. If the queue is empty then null is returned.

Code

The code below demonstrates how to use the poll method:

import java.util.concurrent.ArrayBlockingQueue;
class Poll {
public static void main( String args[] ) {
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
queue.add("1");
queue.add("2");
queue.add("3");
System.out.println("The queue is " + queue);
System.out.println("queue.poll() - " + queue.poll());
System.out.println("The queue is " + queue);
}
}

In the code above,

  • In line 1: Imported the ArrayBlockingQueue from the java.util.concurrent package.

  • In line 4: Created an object for the ArrayBlockingQueue class with the name queue and size 5.

  • In lines 5-7: Used the add method to add three elements to the queue object.

*In line 9: Used the poll method to get and remove the head element of the queue. After calling this method, the head element will be removed from the queue.

Free Resources