Java BlockingQueue Interface

The BlockingQueue interface of the Java Collections framework extends the Queue interface. It allows any operation to wait until it can be successfully performed. For example, if we want to delete an element from an empty queue, then the blocking queue allows the delete operation to wait until the queue contains some elements to be deleted.

There are 2 different classes in BlockingQueue interface.

  1. ▪ ArrayBlockingQueue
  2. ▪ LinkedBlockingQueue

Use BlockingQueue

we must import the java.util.Deque package to use Deque.


                    // Array implementation of BlockingQueue
                    BlockingQueue<String> animal1 = new ArraryBlockingQueue<>();

                    // LinkedList implementation of BlockingQueue
                    BlockingQueue<String> animal2 = new LinkedBlockingQueue<>();
                  

Some of the commonly used methods of the BlockingQueue interface are:

  1. offer() - Inserts the specified element to the blocking queue at the end of the queue. Returns false if the queue is full.
  2. peek() - Returns the head of the blocking queue. Returns null if the queue is empty.
  3. poll() - Removes an element from the blocking queue. Returns null if the queue is empty.
  4. put() - Inserts an element to the blocking queue. If the queue is full, it will wait until the queue has space to insert an element.
  5. take() - Removes and returns an element from the blocking queue. If the queue is empty, it will wait until the queue has elements to be deleted.