Open In App

ArrayBlockingQueue poll() Method in Java

Last Updated : 04 Apr, 2023
Comments
Improve
Suggest changes
1 Like
Like
Report
ArrayBlockingQueue is bounded, blocking queue that stores the elements internally backed by an array.
  • ArrayBlockingQueue class is a member of the Java Collections Framework.
  • Bounded means it will have a fixed size, you can not store number the elements more than the capacity of the queue.
  • The queue also follows FIFO (first-in-first-out) rule for storing and removing elements from the queue.
  • If you try to put an element into a full queue or to take an element from an empty queue then the queue will block you.
There are two types of poll() method depending upon no of parameter passed.
  1. The poll() method retrieves and removes element from head of this queue.If queue is empty then method will return null. Syntax:
    public E poll()
    Return Value: The method returns the element from the head of this queue, or null if this queue is empty. Below programs illustrate poll() method of ArrayBlockingQueue. Program 1:
    Output:
    Queue Contains[423, 233, 356]
    Removing From head: 423
    Queue Contains[233, 356]
    Removing From head: 233
    Queue Contains[356]
    Removing From head: 356
    Queue Contains[]
    Removing From head: null
    Queue Contains[]
    
    Program 2:
    Output:
    removing user having name = Aman
    removing user having name = Sanjeet
    removing user having name = null
    
  2. The poll(long timeout, TimeUnit unit) method retrieves and removes element from head of this queue. If the queue is empty then it will, wait till a specified time for an element to become available. Syntax:
    public E poll(long timeout, TimeUnit unit) throws InterruptedException
    Parameters: The method takes two parameters:
    • timeout (long) - how long to wait before giving up, in units of unit.
    • unit (TimeUnit)- a TimeUnit determining how to interpret the timeout parameter.
    Return Value: The method returns the head of this queue, or null if the specified waiting time elapses before an element is available. Exception: The method throws InterruptedException if interrupted while waiting. Below program illustrates poll(long timeout, TimeUnit unit)method of ArrayBlockingQueue.
    Output:
    Queue Contains[423, 233, 356]
    Removing From head: 423
    Queue Contains[233, 356]
    Removing From head: 233
    Queue Contains[356]
    Removing From head: 356
    Queue Contains[]
    Removing From head: null
    
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ArrayBlockingQueue.html#poll()

Next Article

Similar Reads