BlockingDeque in Java

The BlockingDeque interface is a part of the Java Collections Framework. It gets its name because it blocks illegal operations such as insertion into a full queue or deletion from an empty queue, all of these properties are inbuilt into the structure of this interface. Since it is a deque it is double-ended that is the insertion, deletion, and traversal operations can be performed from both ends. The BlockingDeque is an interface, so we cannot declare any objects with it.

Hierarchy

The BlockingDeque extends from the BlockingQueue interface, which in turn extends from the Queue interface and the Deque interface.

The Hierarchy of BlockingDeque

Note: The Interfaces of the Collection framework may have additional implementing classes and extending interfaces but the above image only shows the hierarchy of BlockingDeque and its implementing classes.

Syntax:

public interface BlockingDeque<E> extends BlockingQueue<E>, Deque<E>

E – The type of the elements in the collection.

Implementing LinkedBlockingDeque Class

The implementing class of BlockingDeque is LinkedBlockingDeque. This class is the implementation of the BlockingDeque and the linked list data structure. The LinkedBlockingDeque can be optionally bounded using a constructor, however, if the capacity is unspecified it is Integer.MAX_VALUE by default. The nodes are added dynamically at the time of insertion obeying the capacity constraints. 



The syntax for creating objects:

LinkedBlockingDeque<?> objectName = new LinkedBlockingDeque<?>();

Example: In the code given below we perform some basic operations on a LinkedBlockingDeque, like creating an object, adding elements, deleting elements, and using an iterator to traverse through the LinkedBlockingDeque.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program for LinkedBlockingDeque
import java.util.concurrent.LinkedBlockingDeque;
import java.util.*;
  
public class LinkedBlockingDequeExample {
  
    public static void main(String[] args) {
          
        // Instantiate an object of LinkedBlockingDeque named lbdq
        LinkedBlockingDeque<Integer> lbdq = new LinkedBlockingDeque<Integer>();
  
        // Add elements using add()
        lbdq.add(134);
        lbdq.add(245);
        lbdq.add(23);
        lbdq.add(122);
        lbdq.add(90);
          
        // Create an iterator to traverse the deque
        Iterator<Integer> lbdqIter = lbdq.iterator();
          
        // Print the elements of lbdq on to the console
        System.out.println("The LinkedBlockingDeque lbdq contains:");
          
        for(int i = 0; i<lbdq.size(); i++)
        {
            System.out.print(lbdqIter.next() + " ");
        }
          
        // Remove 23 and display appropriate message if the
        // operation is successful
        if(lbdq.remove(23))
        {
            System.out.println("\n\nThe element 23 has been removed");
        }
        else
        {
            System.out.println("\n\nNo such element was found");
        }
          
        // Print the elements of lbdq without using iterator
        System.out.println("\nThe LinkedBlockingDeque lbdq"+
                       " after remove operation contains:");
        System.out.println(lbdq);
    }
  
}

chevron_right


Output

The LinkedBlockingDeque lbdq contains:
134 245 23 122 90 

The element 23 has been removed

The LinkedBlockingDeque lbdq after remove operation contains:
[134, 245, 122, 90]


Basic Operations

1. Adding Elements

Elements can be added into a LinkedBlockedDeque in different ways depending on the type of structure we are trying to use it as. The most common method is the add() method using which we can add elements at the end of the deque. We can also use the addAll() method (which is a method of the Collection interface) to add an entire collection to LinkedBlockingDeque. If we wish to use the deque as a queue we can use add() and put().

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program for Adding elements to a LinkedBlockingDeque
import java.util.concurrent.LinkedBlockingDeque;
  
public class AddingElements {
  
    public static void main(String[] args) {
          
        // Instantiate a LinkedBlockingDeque named lbdq1
        LinkedBlockingDeque<Integer> lbdq1 = new LinkedBlockingDeque<Integer>();
          
        // Add elements using add()
        lbdq1.add(145);
        lbdq1.add(89);
        lbdq1.add(65);
        lbdq1.add(122);
        lbdq1.add(11);
          
        // Print the contents of lbdq1 on the console
        System.out.println("Contents of lbdq1: " + lbdq1);
          
        // Instantiate a LinkedBlockingDeque named lbdq2
        LinkedBlockingDeque<Integer> lbdq2 = new LinkedBlockingDeque<Integer>();
          
        // Add elements from lbdq1 using addAll()
        lbdq2.addAll(lbdq1);
          
        // Print the contents of lbdq2 on the console
        System.out.println("\nContents of lbdq2: " + lbdq2);
          
    }
  
}

chevron_right


Output

Contents of lbdq1: [145, 89, 65, 122, 11]

Contents of lbdq2: [145, 89, 65, 122, 11]

2. Accessing Elements

The elements of the LinkedBlockingDeque can be accessed using contains(), element(), peek(), poll(). There are variations of these methods too which are given in the table above along with their descriptions.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program for Accessing the elements of a LinkedBlockingDeque
  
import java.util.concurrent.LinkedBlockingDeque;
  
public class AccessingElements {
  
    public static void main(String[] args) {
          
        // Instantiate an object of LinkedBlockingDeque named lbdq
        LinkedBlockingDeque<Integer> lbdq = new LinkedBlockingDeque<Integer>();
  
        // Add elements using add()
        lbdq.add(22);
        lbdq.add(125);
        lbdq.add(723);
        lbdq.add(172);
        lbdq.add(100);
          
        // Print the elements of lbdq on the console
        System.out.println("The LinkedBlockingDeque, lbdq contains:");
        System.out.println(lbdq);
          
        // To check if the deque contains 22
        if(lbdq.contains(22))
            System.out.println("The LinkedBlockingDeque, lbdq contains 22");
        else
            System.out.println("No such element exists");
  
        // Using element() to retrieve the head of the deque
        int head = lbdq.element();
        System.out.println("The head of lbdq: " + head);
          
        // Using peekLast() to retrieve the tail of the deque
        int tail  = lbdq.peekLast();
        System.out.println("The tail of lbdq: " + tail);
          
    }
  
}

chevron_right


Output

The LinkedBlockingDeque, lbdq contains:
[22, 125, 723, 172, 100]
The LinkedBlockingDeque, lbdq contains 22
The head of lbdq: 22
The tail of lbdq: 100

3. Deleting Elements

Elements can be deleted from a LinkedBlockingDeque using remove(). Other methods such as take() and poll() can also be used in a way to remove the first and the last elements.



Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program for removing elements from a LinkedBlockingDeque
  
import java.util.concurrent.LinkedBlockingDeque;
  
public class RemovingElements {
  
    public static void main(String[] args) {
          
        // Instantiate an object of LinkedBlockingDeque named lbdq
        LinkedBlockingDeque<Integer> lbdq = new LinkedBlockingDeque<Integer>();
          
        // Add elements using add()
        lbdq.add(75);
        lbdq.add(86);
        lbdq.add(13);
        lbdq.add(44);
        lbdq.add(10);
          
        // Print the elements of lbdq on the console
        System.out.println("The LinkedBlockingDeque, lbdq contains:");
        System.out.println(lbdq);
          
        // Remove elements using remove();
        lbdq.remove(86);
        lbdq.remove(44);
          
        // Trying to remove an element
        // that doesn't exist
        // in the LinkedBlockingDeque
        lbdq.remove(1);
          
        // Print the elements of lbdq on the console
        System.out.println("\nThe LinkedBlockingDeque, lbdq contains:");
        System.out.println(lbdq);
  
    }
  
}

chevron_right


Output

The LinkedBlockingDeque, lbdq contains:
[75, 86, 13, 44, 10]

The LinkedBlockingDeque, lbdq contains:
[75, 13, 10]

4. Iterating through the Elements

To iterate through the elements of a LinkedBlockingDeque we can create an iterator and use the methods of the Iterable interface, which is the root of the Collection Framework of Java, to access the elements. The next() method of Iterable returns the element of any collection.

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to iterate through the LinkedBlockingDeque
import java.util.Iterator;
import java.util.concurrent.LinkedBlockingDeque;
  
public class IteratingThroughElements {
  
    public static void main(String[] args) {
          
        // Instantiate an object of LinkedBlockingDeque named lbdq
        LinkedBlockingDeque<Integer> lbdq = new LinkedBlockingDeque<Integer>();
          
        // Add elements using add()
        lbdq.add(166);
        lbdq.add(246);
        lbdq.add(66);
        lbdq.add(292);
        lbdq.add(98);
          
        // Create an iterator to traverse lbdq
        Iterator<Integer> lbdqIter = lbdq.iterator();
          
        // Print the elements of lbdq on to the console
        System.out.println("The LinkedBlockingDeque, lbdq contains:");
          
        for(int i = 0; i<lbdq.size(); i++)
        {
            System.out.print(lbdqIter.next() + " ");
        }        
    }
  
}

chevron_right


Output

The LinkedBlockingDeque, lbdq contains:
166 246 66 292 98 

Methods of BlockingDeque

The BlockingDeque interface has a various method which has to be defined by every implementing class. A deque can be implemented as a queue and as a stack, therefore the BlockingDeque interface provides methods to do the same. The table below provides a list of all the methods and their function.

Method

Description

boolean add(E element) Adds the element to the queue represented by this deque (i.e. at the tail) if possible without violating any capacity restrictions. Returns true if the insertion is successful else throws an exception.
void addFirst(E element) Adds the element at the head of the deque if possible without violating any capacity restrictions. If the operation is not successful then it throws an exception.
void addLast(E element) Adds the element at the tail of the deque if possible without violating any capacity restrictions. If the operation is not successful then it throws an exception.
void push(E element) Pushes the element onto the stack represented by this deque.
void put(E element) Inserts the element into the queue represented by this deque (i.e. at the tail). If the space is not available then it waits for the required space to be available.
void putFirst(E element) Inserts the element at the head of the deque. If the space is not available then it waits for the required space to be available.
void putLast(E element) Inserts the element at the tail of the deque. If the space is not available then it waits for the required space to be available.
boolean offer(E element) Inserts the element into the queue represented by this deque (i.e. at the tail) if possible immediately without violating any capacity restrictions. Returns true on successful insertion and false otherwise.
boolean offer(E element, long time, TimeUnit unit) Inserts the element into the queue represented by this deque (i.e. at the tail) immediately if possible, else waits for the time specified for the space to become available.
boolean offerFirst(E element) Inserts the element at the head of the deque if possible immediately without violating any capacity restrictions. Returns true on successful insertion and false otherwise.
boolean offerFirst(E element, long time, TimeUnit unit) Inserts the element at the head of the deque immediately if possible, else waits for the time specified for the space to become available.
boolean offerLast(E element) Inserts the element at the tail of the deque if possible immediately without violating any capacity restrictions. Returns true on successful insertion and false otherwise.
boolean offerLast(E element, long time, TimeUnit unit) Inserts the element at the tail of the deque immediately if possible, else waits for the time specified for the space to become available.
int size() Returns the number of elements in the deque.
boolean contains(Object obj) Checks if the deque has the specified element, returns true if yes else returns false.
E element() Retrieves the head of the queue represented by this deque.
Iterator<E> iterator() Creates and returns an iterator for this deque.
E peek() Returns the head of the queue represented by this deque if present else returns null.
E poll() Retrieves and removes the head of the queue represented by this deque if present else returns null.
E poll(long time, TimeUnit unit) Retrieves and removes the head of the queue represented by this deque. If no element is present then it waits for the specified time for it to become available.
E pollFirst(long time, TimeUnit unit) Retrieves and removes the head of the deque. If no element is present then it waits for the specified time for it to become available.
E pollLast(long time, TimeUnit unit) Retrieves and removes the tail of the deque. If no element is present then it waits for the specified time for it to become available.
E remove() Retrieves and removes the head of the queue represented by this deque.
boolean remove(Object obj) Removes the first occurrence of the specified element from the deque.
boolean removeFirstOccurance(Object obj) Removes the first occurrence of the specified element from the deque.
boolean removeLastOccurance(Object obj) Removes the last occurrence of the specified element from the deque.
E take() Retrieves and removes the head of the queue represented by this deque. If required waiting for the element to become available.
E takeFirst() Retrieves and removes the head of the deque. If required waiting for the element to become available.
E takeLast() Retrieves and removes the tail of the deque. If required waiting for the element to become available.

Here,

E – The type of elements in the collection.

TimeUnit – An enum that represents the time durations.

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.