The poll(long timeout, TimeUnit unit) method of BlockingQueue interface returns the head of BlockingQueue by removing that element from the queue. It can be said that this method retrieves and removes element from head of this LinkedBlockingQueue. If queue is empty, then poll() method will wait till a specified time for an element to become available.
public E poll(long timeout, TimeUnit unit) throws
Parameters: This method takes two mandatory parameters:
- timeout– how long to wait, in units of unit.
- unit– a TimeUnit for the timeout parameter.
Return Value: This method retrieves and removes element from head of this LinkedBlockingQueue, or null if the specified waiting time elapses before an element is available.
Exception This method throws InterruptedException if method interrupted while waiting for an element to become available.
Note: The poll() method of BlockingQueue has been inherited from the Queue class in Java.
Below programs illustrates poll(long timeout, TimeUnit unit) method of BlockingQueue:
Items in Queue are [Ravi, Suraj, Harsh] Removing item From head: Ravi Now Queue Contains[Suraj, Harsh] Removing item From head: Suraj Now Queue Contains[Harsh] Removing item From head: Harsh Now Queue Contains Removing item From head: null Now Queue Contains
Items in Queue are [Gopal, GFG] Removing item From head: Gopal Now Queue Contains[GFG]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.