ArrayBlockingQueue in Java


ArrayBlockingQueue Java MultithreadingViews 1125

ArrayBlockingQueue in Java

ArrayBlockingQueue is a class in Java that implements the BlockingQueue interface. It is a bounded BlockingQueue that stores elements internally in the form of an array. Hence it implements the FIFO concept(First In First Out) which means that the element that we insert first will be retrieved first. The head of the queue is the element in the queue that stays for a long time whereas the tail of the queue contains the element that stays for a short time.

An ArrayBlockingQueue implements the functionality of a BlockingQueue. This means that it blocks the thread during insertion operation if the queue has no capacity. It waits until there is some available space in the queue to insert elements. Similarly, it blocks a thread when we try to remove an element when the queue is empty. It waits until there is some element to retrieve from the queue.

We can specify the capacity of the ArrayBlockingQueue while creating an instance of the same.

Hierarchy

ArrayBlockingQueue in Java

Constructors of ArrayBlockingQueue

Below are the constructors of the ArrayBlockingQueue class in Java:

ConstructorDescriptionSynatx
ArrayBlockingQueue<int capacity)Creates an ArrayBlockingQueue with the specified capacityArrayBlockingQueue aq = new ArrayBlockingQueue(int capacity);
ArrayBlockingQueue(int capacity, boolean fair)Creates an ArrayBlockingQueue with the specified capacity and access policyArrayBlockingQueue aq = new ArrayBlockingQueue(int capacity, boolean fair);
ArrayBlockingQueue(int capacity, boolean fair, Collection c)Creates an ArrayBlockingQueue with the specified capacity, access policy and elements in the specified collectionArrayBlockingQueue aq = new ArrayBlockingQueue(int capacity, boolean fair, Collection c);

Methods of Java ArrayBlockingQueue

Below are the methods of the ArrayBlockingQueue class in Java:

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

The below example shows how to insert elements into an ArrayBlockingQueue using add(), offer() and put() methods. Here, we have initialized the BlcokingQueue with capacity 5. Hence we can add only 5 elements, if we try to add the 6th element, it blocks the queue until there is available space.

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ArrayBlockingQueueDemo {

  public static void main(String[] args) throws InterruptedException {
    ArrayBlockingQueue<String> bq = new ArrayBlockingQueue<String>(5);
    bq.add("Red");
    bq.add("Green");
    bq.add("Blue");
    
    System.out.println(bq);
    
    bq.offer("Yellow");
    System.out.println(bq);
    
    bq.put("Orange");
    System.out.println(bq);
  }

}
[Red, Green, Blue]
[Red, Green, Blue, Yellow]
[Red, Green, Blue, Yellow, Orange]

Example: Remove elements

This example shows how to remove elements from the queue using the remove(), poll() and take() methods. The poll() and take() removes the head element from the queue.

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class ArrayBlockingQueueDemo {

  public static void main(String[] args) throws InterruptedException {
    ArrayBlockingQueue<String> bq = new ArrayBlockingQueue<String>(5);
    System.out.println("Inserting elements...");
    bq.add("Red");
    bq.add("Green");
    bq.add("Blue");
    
    System.out.println(bq);
  
    bq.offer("Yellow");
    System.out.println(bq);
    
    bq.put("Orange");
    System.out.println(bq);
    
    System.out.println("Removing elements...");
    bq.remove("Yellow");
    System.out.println(bq);
    
    bq.poll();
    System.out.println(bq);
    
    bq.take();
    System.out.println(bq);
  }

}
Inserting elements...
[Red, Green, Blue]
[Red, Green, Blue, Yellow]
[Red, Green, Blue, Yellow, Orange]
Removing elements...
[Red, Green, Blue, Orange]
[Green, Blue, Orange]
[Blue, Orange]

Example: Access elements

This example shows how to retrieve the head element using the element() and peek() method. These methods will only retrieve the values and does not remove them from the queue. We can use the retainAll() method to retain only the collection elements and remove the other elements.

import java.util.concurrent.ArrayBlockingQueue;

public class AccessArrayBQ {

  public static void main(String[] args) {
    ArrayBlockingQueue<String> bq = new ArrayBlockingQueue<String>(10);
  
    bq.add("Red");
    bq.add("Green");
    bq.add("Blue");
    bq.add("Yellow");
    bq.add("Orange");
    
    System.out.println("Element method output: " + bq.element());
    System.out.println("Peek method output: " + bq.peek());
    
    ArrayBlockingQueue<String> c = new ArrayBlockingQueue<String>(2);
    c.add("Black");
    c.add("Brown");
    bq.addAll(c);
    System.out.println("Elements in Queue after addAll: " + bq);
    
    bq.retainAll(c);
    System.out.println("RetainAll output: " + bq);
  }

}
Element method output: Red
Peek method output: Red
Elements in Queue after addAll: [Red, Green, Blue, Yellow, Orange, Black, Brown]
RetainAll output: [Black, Brown]

Example: Iterate elements

The below example uses the iterate() method of the Iterator to traverse through all the elements in the queue. It uses the next() method to navigate to the next element.

import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;

public class AccessArrayBQ {

  public static void main(String[] args) {
    ArrayBlockingQueue<String> bq = new ArrayBlockingQueue<String>(10);
  
    bq.add("Red");
    bq.add("Green");
    bq.add("Blue");
    bq.add("Yellow");
    bq.add("Orange");
    
    Iterator<String> it = bq.iterator();
    while(it.hasNext())
      System.out.println(it.next());
    
  }

}
Red
Green
Blue
Yellow
Orange

 

Reference

Translate ยป