VOOZH about

URL: https://www.geeksforgeeks.org/java/blockingqueue-take-method-in-java-with-examples/

⇱ BlockingQueue take() method in Java with examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

BlockingQueue take() method in Java with examples

Last Updated : 23 Aug, 2021

The take() method of BlockingQueue interface is used to retrieve and remove the head of this queue. If the queue is empty then it will wait until an element becomes available. This method is more efficient if working on threads and using BlockingQueue in that process. So the thread that initially calls take() goes to sleep if there is no element available, letting other threads do whatever they need to do.
 

Syntax:  

public E take() throws InterruptedException


Return Value: This method returns value at the head of this BlockingQueue. If the queue is empty then it will wait until an element becomes available.
Exception: This method throws following exceptions:  

  • InterruptedException- When the interruption occurs at time of waiting for an element to become available if queue is empty.


Note: The take() method of BlockingQueue has been inherited from the Queue class in Java.
Below programs illustrates take() method of BlockingQueue interface:
Program 1: 


Output: 
Items in Queue are [Ravi, Suraj, Harsh, Sayan]
Removed Item from head is Ravi
Remaining Items in Queue are [Suraj, Harsh, Sayan]
Removed Item from head is Suraj
Remaining Items in Queue are [Harsh, Sayan]

 

Program 2: 


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

 
Comment