What is ArrayBlockingQueue ? How to add and remove elements from ArrayBlockingQueue ?

ArrayBlockingQueue is a bounded BlockingQueue backed by an array. This queue orders elements in FIFO (first-in-first-out). The head of the queue is the element which has been on the queue for the longest time. The tail of the queue is that element that has been on the queue for the shortest time. New elements are added at the tail of the queue, and the queue retrieval operations remove elements from the head of the queue.

ArrayBlockingQueue is the classic example of a "bounded buffer". A fixed-sized array is the backing data structure for ArrayBlockingQueue. We need to pass the capacity of ArrayBlockingQueue while creating the object. Once created, the capacity cannot be changed. Remember array is a fixed size data structure that can not be altered once created. Attempts to put an element into a full queue will result in the operation blocking; attempts to take an element from an empty queue will similarly block.

This class supports an optional fairness policy for ordering waiting producer and consumer threads. By default, this ordering is not guaranteed. However, a queue constructed with fairness set to true grants threads access in FIFO order. Fairness generally decreases throughput but reduces variability and avoids starvation.

This class and its iterator implement all of the optional methods of the Collection and Iterator interfaces.

Following are the ways to adding elements to an ArrayBlockingQueue :

We can add an element in an ArrayBlockingQueue by add () or offer() method. offer() inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions, returning true upon success and false if no space is currently available. Where as add() throws an exception if it is not able to add the element in the queue due to capacity restrictions. When using a capacity-restricted queue, offer() method is generally preferable to add, which can fail to insert an element only by throwing an exception. Here throwing exceptions and returning boolean values are the implementation of blocking mechanism. To read about all Blocking mechanism please check here.

Here in the following example we have 2 ArrayBlockingQueue of size 5. And we will try to add 6 elements in each of the blocking queue using offer() and add() method. 

BlockingQueue blockingQueue1 = new ArrayBlockingQueue<>(5);
BlockingQueue blockingQueue2 = new ArrayBlockingQueue<>(5);

Both the methods will be able to add 5 elements, but offer will returns false for the sixth elements where as add will throws and exception for the sixth element.

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

class MyArrayBlockingQueue {

    // Let's create a blocking queue that can hold at most 5 elements.
    BlockingQueue blockingQueue1 = new ArrayBlockingQueue<>(5);
    BlockingQueue blockingQueue2 = new ArrayBlockingQueue<>(5);

    public boolean addByOffer(String s) {
        return blockingQueue1.offer(s);
    }

    public boolean addByAdd(String s) {
        return blockingQueue2.add(s);
    }
}

public class TestArrayBlockingQueue {
    public static void main(String args[]) {
        MyArrayBlockingQueue myArrayBlockingQueue = new MyArrayBlockingQueue();
        System.out.println("Adding 6 elements by offer ()");
        for (int i = 0; i < 6; i++) {
            System.out.println("Element no :" + (i+1) + "adding by offer() : " + myArrayBlockingQueue.addByOffer("String" + i));
        }
        System.out.println("=============================");
        System.out.println("Adding 6 elements by add ()");
        for (int i = 0; i < 6; i++) {
            System.out.println("Element no :" + (i+1) + "adding by add() : " + myArrayBlockingQueue.addByAdd("String" + i));
        }
    }
}

Output of the program :

Adding 6 elements by offer ()
Element no :1adding by offer() : true
Element no :2adding by offer() : true
Element no :3adding by offer() : true
Element no :4adding by offer() : true
Element no :5adding by offer() : true
Element no :6adding by offer() : false
=============================
Adding 6 elements by add ()
Element no :1adding by add() : true
Element no :2adding by add() : true
Element no :3adding by add() : true
Element no :4adding by add() : true
Element no :5adding by add() : true
Exception in thread "main" java.lang.IllegalStateException: Queue full
    at java.util.AbstractQueue.add(AbstractQueue.java:98)
    at java.util.concurrent.ArrayBlockingQueue.add(ArrayBlockingQueue.java:312)
    at com.tuturself.concurrenttest.MyArrayBlockingQueue.addByAdd(TestArrayBlockingQueue.java:17)
    at com.tuturself.concurrenttest.TestArrayBlockingQueue.main(TestArrayBlockingQueue.java:31)

 Following are the ways to removing elements from an ArrayBlockingQueue :

We can remove an element from an ArrayBlockingQueue by poll () or remove() method. poll() retrieves and removes the head of the queue and returns null when the queue is empty where as remove() also retrieves and removes the head of the queue but throws an exception if this queue is empty.

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

class MyArrayBlockingQueue {

    // Let's create a blocking queue that can hold at most 5 elements.
    BlockingQueue blockingQueue1 = new ArrayBlockingQueue<>(5);
    BlockingQueue blockingQueue2 = new ArrayBlockingQueue<>(5);

    public boolean addByOffer(String s) {
        return blockingQueue1.offer(s);
    }
    
    public String removeByPoll() {
        return blockingQueue1.poll();
    }

    public boolean addByAdd(String s) {
        return blockingQueue2.add(s);
    }
    
    public String removeByRemove() {
        return blockingQueue2.remove();
    }
}

public class TestArrayBlockingQueue {
    public static void main(String args[]) {
        MyArrayBlockingQueue myArrayBlockingQueue = new MyArrayBlockingQueue();
        System.out.println("Adding 5 elements by offer ()");
        for (int i = 0; i < 5; i++) {
            System.out.println("Element no :" + (i+1) + " adding by offer() : " + myArrayBlockingQueue.addByOffer("String" + i));
        }
        System.out.println("------------------------------");
        System.out.println("Removing 6 elements by poll ()");
        for (int i = 0; i < 6; i++) {
            System.out.println("Element no :" + (i+1) + " removed by poll() : " + myArrayBlockingQueue.removeByPoll());
        }
        
        System.out.println("=============================");
        System.out.println("Adding 5 elements by add ()");
        for (int i = 0; i < 5; i++) {
            System.out.println("Element no :" + (i+1) + " adding by add() : " + myArrayBlockingQueue.addByAdd("String" + i));
        }
        System.out.println("------------------------------");
        System.out.println("Removing 6 elements by remove ()");
        for (int i = 0; i < 6; i++) {
            System.out.println("Element no :" + (i+1) + " removed by remove() : " + myArrayBlockingQueue.removeByRemove());
        }
    }
}

Output of the program:

Adding 5 elements by offer ()
Element no :1 adding by offer() : true
Element no :2 adding by offer() : true
Element no :3 adding by offer() : true
Element no :4 adding by offer() : true
Element no :5 adding by offer() : true
------------------------------
Removing 6 elements by poll ()
Element no :1 removed by poll() : String0
Element no :2 removed by poll() : String1
Element no :3 removed by poll() : String2
Element no :4 removed by poll() : String3
Element no :5 removed by poll() : String4
Element no :6 removed by poll() : null
=============================
Adding 5 elements by add ()
Element no :1 adding by add() : true
Element no :2 adding by add() : true
Element no :3 adding by add() : true
Element no :4 adding by add() : true
Element no :5 adding by add() : true
------------------------------
Removing 6 elements by remove ()
Element no :1 removed by remove() : String0
Element no :2 removed by remove() : String1
Element no :3 removed by remove() : String2
Element no :4 removed by remove() : String3
Element no :5 removed by remove() : String4
Exception in thread "main" java.util.NoSuchElementException
    at java.util.AbstractQueue.remove(AbstractQueue.java:117)
    at com.tuturself.concurrenttest.MyArrayBlockingQueue.removeByRemove(TestArrayBlockingQueue.java:25)
    at com.tuturself.concurrenttest.TestArrayBlockingQueue.main(TestArrayBlockingQueue.java:50)

 

core java 12 Java Concurrent Packages 12

FOLLOW US ON LinkedIn



Explore Tutu'rself