There is two types of poll() method in LinkedBlockingQueue.
poll()
The
poll() method of
LinkedBlockingQueue returns the head of LinkedBlockingQueue by removing that element from queue. It can be said that this method retrieves and removes element from head of this LinkedBlockingQueue. If queue is empty then poll method returns null.
Syntax:
public E poll()
Return Value: This method retrieves and removes element from head of this LinkedBlockingQueue. If the queue is empty, then it returns null.
Below programs illustrates poll() method of LinkedBlockingQueue class:
Program 1: Removing elements from the LinkedBlockingQueue using poll() method where LinkedBlockingQueue contains list of names.
Output:
Items in Queue are [Ravi, Suraj, Harsh, Sayan]
Removed Item is Ravi
Remaining Items in Queue are [Suraj, Harsh, Sayan]
Removed Item is Suraj
Remaining Items in Queue are [Harsh, Sayan]
Program 2: Removing elements from LinkedBlockingQueue which contains list of Employees and if queue is empty print null.
Output:
Removed Item is :
Employee Name - Ravi
Employee Position - Tester
Employee Salary - 39000
Size of list :1
Removed Item is :
Employee Name - Sanjeet
Employee Position - Manager
Employee Salary - 98000
Size of list :0
Removed Item is : null
poll(long timeout, TimeUnit unit)
The
poll(long timeout, TimeUnit unit) method of
LinkedBlockingQueue returns the head of LinkedBlockingQueue 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.
Syntax:
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.
Below programs illustrates poll(long timeout, TimeUnit unit) method of LinkedBlockingQueue class:
Program 1: Removing elements from the LinkedBlockingQueue using poll() method where LinkedBlockingQueue contains list of names.