LinkedBlockingQueue in Java


Java LinkedBlockingQueue MultithreadingViews 1603

LinkedBlockingQueue in Java

LinkedBlockingQueue is a class in Java that implements the BlockingQueue interface. It is part of the Collections framework and is present in the java.util.concurrent package. It is a BlockingQueue that internally implements a doubly-linked list structure. The element that is present in the queue for a long time represents the head element and the element that we recently insert represents the tail element. Since it is a blocking queue, it blocks the thread during insertion and removal operation if the queue does not have enough capacity or if empty respectively.

LinkedBlockingQueue is bounded if we specify the capacity as a parameter in the constructor. If not, it is unbounded and capacity is equal to Integer.MAX_VALUE.  Since the LinkedBlockingQueue uses a LinkedList data structure, it is thread-safe in a multithreading environment.

Hierarchy

LinkedBlockingQueue in Java

Constructors of Java LinkedBlockingQueue

Below are the constructors present in the Java LinkedBlockingQueue class.

ConstructorDescription
LinkedBlockingQueue()Creates a LinkedBlockingQueue with capacity as Integer.MAX_VALUE
LinkedBlockingQueue(int capacity)Creates a LinkedBlockingQueue with the specified capacity
LinkedBlockingQueue(Collection c)Creates a LinkedBlockingQueue with the specified collection elements

Methods

Below are the methods of the LinkedBlockingQueue class in Java. It also implements the methods of the Collection and Iterator interface.

MethodsDescription
boolean add(Element e)Inserts an element to the queue
void clear()Clears the queue by removing all the elements in the queue
boolean contains(Object o)Returns true if the queue contains the specified element
int drainTo(Collection c)Removes all the elements from the queue and moves it to the specified collection. It returns the number of elements transferred
int drainTo(Collection c, int maxElements)Removes the maximum number of elements from the queue and adds them to the specified collection
void forEach(Consumer action)Performs the specified action for each element in the queue.
Iterator iterator()Returns an iterator over the elements in the queue
boolean offer(Integer e)Inserts the specified element
boolean offer(Integer e, long timeout, TimeUnit timeunit)Inserts the specified element to the queue after waiting for the specified timeout if space is unavailable
Element peek()Returns the head element in the queue
Element poll(long timeout, TimeUnit timeunit)Retrieves and removes the head of the element after waiting for specified time
void put(Element e)Inserts the specified element into the queue
int remainingCapacity()Returns the number of elements it can accept without blocking the queue
boolean remove(Object e)Removes the specified element from the queue
boolean removeAll(Collection c)Removes all the collection elements in the queue
boolean retainAll(Collection c)Retains all the collection elements in the queue and removes the other elements
int size()Returns the size of the queue
Spliterator spliterator()Returns a spliterator over the elements
Integer take()Retrieves and removes the head of the queue

Example: Insert elements

Below is an example of inserting elements into the LinkedBlockingQueue in Java using the add(), put(), and offer() methods. We create a LinkedBlockingQueue with default capacity. The put method throws an exception if the queue reaches its maximum quantity.

import java.util.concurrent.LinkedBlockingQueue;

public class LinkedBlockingQueueDemo {

  public static void main(String[] args) throws InterruptedException {
    LinkedBlockingQueue<Integer> lb = new LinkedBlockingQueue<Integer>();
    lb.add(10);
    lb.add(20);
    lb.add(30);
    
    lb.put(40);
    lb.offer(50);
    
    System.out.println(lb);

  }

}
[10, 20, 30, 40, 50]

Example: Remove elements

Below is an example of removing elements from the LinkedBlockingQueue in Java using the remove(), poll() and take() methods. These methods always remove the head element from the queue. We can also remove a specific element by using the remove() method.

import java.util.concurrent.LinkedBlockingQueue;

public class LinkedBlockingQueueDemo {

  public static void main(String[] args) throws InterruptedException {
    System.out.println("Inserting elements...");
    LinkedBlockingQueue<Integer> lb = new LinkedBlockingQueue<Integer>(5);
    lb.add(10);
    lb.add(20);
    lb.add(30);
    
    lb.put(40);
    lb.offer(50);
    
    System.out.println(lb);
    
    System.out.println("Removing elements...");
    
    lb.remove();
    lb.remove(40);
    
    lb.poll();
    lb.take();
    System.out.println(lb);

  }

}
Inserting elements...
[10, 20, 30, 40, 50]
Removing elements...
[50]

Example: Access elements

The below example shows how to access elements in the LinkedBlockingQueue using the element() and peek() methods. It returns the head element of the queue. The retainAll() method retains all the elements in the specified collection and removes the other elements from the queue.

import java.util.concurrent.LinkedBlockingQueue;

public class LinkedBlockingQueueDemo {

  public static void main(String[] args) throws InterruptedException {
    System.out.println("Inserting elements...");
    LinkedBlockingQueue<Integer> lb = new LinkedBlockingQueue<Integer>();
    lb.add(10);
    lb.add(20);
    lb.add(30);
    
    lb.put(40);
    lb.offer(50);
    
    LinkedBlockingQueue<Integer> lbq = new LinkedBlockingQueue<Integer>();
    lbq.add(60);
    lbq.add(70);
    lb.addAll(lbq);
    
    System.out.println(lb);
    System.out.println("Element method output: " + lb.element());
    System.out.println("Peek method output: " + lb.peek());
    lb.retainAll(lbq);
    System.out.println("RetainAll output: " + lb);
    

  }

}
Inserting elements...
[10, 20, 30, 40, 50, 60, 70]
Element method output: 10
Poll method output: 10
RetainAll output: [60, 70]

Example: Iterate elements

We can iterate through all the elements in LinkedBlockingQueue using the iterator method. Using the next() method, we can access each element in the queue.

import java.util.Iterator;
import java.util.concurrent.LinkedBlockingQueue;

public class LinkedBlockingQueueDemo {

  public static void main(String[] args) throws InterruptedException {
    LinkedBlockingQueue<Integer> lb = new LinkedBlockingQueue<Integer>();
    lb.add(10);
    lb.add(20);
    lb.add(30);
    
    lb.put(40);
    lb.offer(50);
    
    Iterator<Integer> it = lb.iterator();
    while(it.hasNext())
      System.out.println(it.next());

  }

}
10
20
30
40
50

 

Reference

Translate »