Skip to content
Related Articles

Related Articles

BlockingDeque in Java
  • Last Updated : 24 Sep, 2020

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 (double-ended queue) 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.

BlockingDeque Usage in Java

Hierarchy

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

BlockingDeque in Java

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>

Here, E is the type of elements in the collection.



Classes that Implement BlockingDeque

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.  To use BlockingDeque in your code, use this import statement.

import java.util.concurrent.BlockingDeque;
                    (or)
import java.util.concurrent.*;

The syntax for creating objects:

LinkedBlockingDeque<?> objectName = new LinkedBlockingDeque<?>();
                (or)
BlockingDeque<?> 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 BlockingDeque
import java.util.concurrent.*;
import java.util.*;
  
public class BlockingDequeExample {
  
    public static void main(String[] args) {
          
        // Instantiate an object using LinkedBlockingDeque named lbdq
        BlockingDeque<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.*;
  
public class AddingElements {
  
    public static void main(String[] args) {
          
        // Instantiate a LinkedBlockingDeque named lbdq1
        BlockingDeque<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.*;
  
public class AccessingElements {
  
    public static void main(String[] args) {
          
        // Instantiate an object of LinkedBlockingDeque named lbdq
        BlockingDeque<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.*;
  
public class RemovingElements {
  
    public static void main(String[] args) {
          
        // Instantiate an object of LinkedBlockingDeque named lbdq
        BlockingDeque<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.*;
  
public class IteratingThroughElements {
  
    public static void main(String[] args) {
          
        // Instantiate an object of LinkedBlockingDeque named lbdq
        BlockingDeque<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.
boolean contains​(Object o) Returns true if this deque contains the specified element.
E element() Retrieves the head of the queue represented by this deque.
Iterator<E> iterator() Returns an iterator over the elements in this deque in the proper sequence.
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.
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.
void push​(E e) Pushes an element onto the stack represented by this deque (in other words, at the head of this deque) if it is possible to do so immediately without violating capacity restrictions, throwing an IllegalStateException if no space is currently available.
void put​(E e) Inserts the specified element into the queue represented by this deque (in other words, at the tail of this deque), waiting if necessary for space to become available.
void putFirst​(E e) Inserts the specified element at the front of this deque, waiting if necessary for space to become available.
void putLast​(E e) Inserts the specified element at the end of this deque, waiting if necessary for space 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.
int size() Returns the number of elements in this 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.

Methods declared in interface java.util.concurrent.BlockingQueue

METHOD

DESCRIPTION

 drainTo​(Collection<? super E> c) Removes all available elements from this queue and adds them to the given collection.
drainTo​(Collection<? super E> c, int maxElements) Removes at most the given number of available elements from this queue and adds them to the given collection.
remainingCapacity() Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking, or Integer.MAX_VALUE if there is no intrinsic limit.

Methods declared in interface java.util.Collection

METHOD

DESCRIPTION

 clear() Removes all of the elements from this collection (optional operation).
containsAll​(Collection<?> c) Returns true if this collection contains all of the elements in the specified collection.
equals​(Object o) Compares the specified object with this collection for equality.
hashCode() Returns the hash code value for this collection.
isEmpty() Returns true if this collection contains no elements.
parallelStream() Returns a possibly parallel Stream with this collection as its source.
removeAll​(Collection<?> c) Removes all of this collection’s elements that are also contained in the specified collection (optional operation).
removeIf​(Predicate<? super E> filter) Removes all of the elements of this collection that satisfy the given predicate.
retainAll​(Collection<?> c) Retains only the elements in this collection that are contained in the specified collection (optional operation).
spliterator() Creates a Spliterator over the elements in this collection.
stream() Returns a sequential Stream with this collection as its source.
toArray() Returns an array containing all of the elements in this collection.
toArray​(IntFunction<T[]> generator) Returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.
toArray​(T[] a) Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.

Methods declared in interface java.util.Deque

METHOD

DESCRIPTION

addAll​(Collection<? extends E> c) Adds all of the elements in the specified collection at the end of this deque, as if by calling addLast(E) on each one, in the order that they are returned by the collection’s iterator.
descendingIterator() Returns an iterator over the elements in this deque in reverse sequential order.
getFirst() Retrieves, but does not remove, the first element of this deque.
getLast() Retrieves, but does not remove, the last element of this deque.
peekFirst() Retrieves, but does not remove, the first element of this deque, or returns null if this deque is empty.
peekLast() Retrieves, but does not remove, the last element of this deque, or returns null if this deque is empty.
pollFirst() Retrieves and removes the first element of this deque, or returns null if this deque is empty.
pollLast() Retrieves and removes the last element of this deque, or returns null if this deque is empty.
pop() Pops an element from the stack represented by this deque.
removeFirst() Retrieves and removes the first element of this deque.
removeLast() Retrieves and removes the last element of this deque.

Methods declared in interface java.lang.Iterable

METHOD

DESCRIPTION

forEach​(Consumer<? super T> action) Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.

The behavior of BlockingDeque Methods

The following are the methods provided by the BlockingDeque for insertion, removal, and examine operations on the deque. Each of the four sets of methods behaves differently if the requested operation is not satisfied immediately. 

  • Throws Exception: An exception will be thrown, if the requested operation is not satisfied immediately.
  • Special value: A special value is returned if the operation is not satisfied immediately.
  • Blocks: The method call is blocked if the attempted operation is not satisfied immediately and it waits until it gets executed.
  • Times out: A special value is returned telling whether the operation succeeded or not. If the requested operation is not possible immediately, the method call blocks until it is, but waits no longer than the given timeout. 

 

Methods on First Element (Head of Deque)

Operation Throws Exception  Special value  Blocks  Times out
Insert  addFirst(e) offerFirst(e) putFirst(e)  offerFirst(e, timeout, timeunit)
Remove removeFirst()  pollFirst()  takeFirst()  pollFirst(timeout, timeunit)
Examine  getFirst()  peekFirst()  not applicable  not applicable

Methods on Last Element (Tail of Deque)

Operation Throws Exception  Special value  Blocks  Times out
Insert  addLast(e)  offerLast(e)  putLast(e)  offerLast(e, timeout, timeunit)
Remove removeLast()  pollLast()  takeLast()  pollLast(timeout, timeunit)
Examine getLast()  peekLast()  not applicable  not applicable 

We know that we can insert, remove, and examine elements from both directions in the BlockingDeque. Since BlockingDeque extends BlockingQueue, the methods for insertion, removal, and examination operations acting on a direction on BlockingDeque are similar to BlockingQueue. The following comparison explains the same.

Operation

BlockingQueue Method 

Equivalent BlockingDeque Method

Insert add(e) addLast(e)
offer(e)  offerLast(e)
put(e)  putLast(e)
offer(e, time, unit)  offerLast(e, time, unit)
Remove remove()  removeFirst()
poll()  pollFirst()
take()  takeFirst()
poll(time, unit)  pollFirst(time, unit)
Examine element()  getFirst()
peek()  peekFirst()

Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/BlockingDeque.html

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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :