Open In App

Java Program to Implement ArrayBlockingQueue API

Improve
Improve
Like Article
Like
Save
Share
Report

ArrayBlockingQueue class is a member of the Java Collection framework. ArrayBlockingQueue is a bounded blocking queue. The term bounded, means that the size of the Queue is fixed and cannot be changed. Any attempt to put element/elements into a full queue will lead to blocking operation. Similarly, any attempt to remove element(s) from an empty queue will lead to a blocking operation.

This bound size feature of ArrayBlockingQueue can be achieved by initially passing capacity as the parameter in the constructor of ArrayBlockingQueue. This queue orders elements FIFO (first-in-first-out). It means that elements can be inserted at the tail of the queue and can be removed from the head of the queue.

The tail of the queue has the newest element while the head of the queue has the oldest one. 

This class extends AbstractQueue<E> and implements Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E> interfaces.

Syntax:

public class ArrayBlockingQueue<E> extends AbstractQueue<E> implements BlockingQueue<E>, Serializable

// Here, E is the type of elements stored in the collection

Basic Operation 

  • add​(E e): Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue’s capacity, returning true upon success and throwing an IllegalStateException if this queue is full.
  • clear(): Atomically removes all of the elements from this queue.
  • contains​(Object o) – Returns true if this queue contains the specified element.
  • 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.
  • forEach​(Consumer<? super E> action) – Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.
  • iterator() – Returns an iterator over the elements in this queue in the proper sequence.
  • offer​(E e) – Inserts the specified element at the tail of this queue if it is possible to do so immediately without exceeding the queue’s capacity, returning true upon success and false if this queue is full.
  • offer​(E e, long timeout, TimeUnit unit) – Inserts the specified element at the tail of this queue, waiting up to the specified wait time for space to become available if the queue is full.
  • put​(E e) – Inserts the specified element at the tail of this queue, waiting for space to become available if the queue is full.
  • remainingCapacity() – Returns the number of additional elements that this queue can ideally (in the absence of memory or resource constraints) accept without blocking.
  • remove​(Object o) – Removes a single instance of the specified element from this queue, if it is present.
  • 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).
  • size() – Returns the number of elements in this queue.
  • spliterator() – Returns a Spliterator over the elements in this queue.
  • toArray() – Returns an array containing all of the elements in this queue, in the proper sequence.
  • toArray​(T[] a) – Returns an array containing all of the elements in this queue, in proper sequence; the runtime type of the returned array is that of the specified array.
  • take() – Retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Java




import java.util.Collection;
import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
 
public class ArrayBlockingQueueImpl<E> {
    private ArrayBlockingQueue<E> arrayBlockingQueue;
 
    // constructor to create object of ArrayBlockingQueue
    // class with the specified capacity.
    public ArrayBlockingQueueImpl(int cap)
    {
        arrayBlockingQueue = new ArrayBlockingQueue<E>(cap);
    }
 
    // constructor to create object of ArrayBlockingQueue
    // class with the specified capacity and specified
    // access policy.
    public ArrayBlockingQueueImpl(int cap, boolean fair)
    {
        arrayBlockingQueue
            = new ArrayBlockingQueue<>(cap, fair);
    }
 
    // constructor to create object of ArrayBlockingQueue
    // class with the specified capacity and specified
    // access initially containing the elements of the given
    // collection.
    public ArrayBlockingQueueImpl(
        int cap, boolean fair,
        Collection<? extends E> collection)
    {
        arrayBlockingQueue = new ArrayBlockingQueue<E>(
            cap, fair, collection);
    }
 
    // method used to append a element to queue's
    // tail.Return true upon successful operation else throw
    // IllegalStateException if this queue reached capacity.
    boolean add(E e) { return arrayBlockingQueue.add(e); }
 
    // method used to removes all elements from the queue
    void clear() { arrayBlockingQueue.clear(); }
 
    // method used to check it queue contains specified
    // element.
    public boolean contains(Object o)
    {
        return arrayBlockingQueue.contains(o);
    }
 
    // method used clear the queue and add all the elements
    // to specified collection.
    public int drainTo(Collection<? super E> c)
    {
        return arrayBlockingQueue.drainTo(c);
    }
 
    // method used to remove at most specified number of
    // elements from the queue and adds them to the
    // specified collection.
    public int drainTo(Collection<? super E> c,
                       int maxElements)
    {
        return arrayBlockingQueue.drainTo(c, maxElements);
    }
 
    // method used to return an iterator over the elements
    // in the queue.This iterator could be used for
    // traversing the element of queue.
    public Iterator<E> iterator()
    {
        return arrayBlockingQueue.iterator();
    }
 
    // method used to append specified element to queue's
    // tail.Return true upon successful operation else
    // return false.
    public boolean offer(E e)
    {
        return arrayBlockingQueue.offer(e);
    }
 
    // method used to insert the specified element at the
    // tail of the queue
    public boolean offer(E e, long timeout, TimeUnit unit)
        throws InterruptedException
    {
        return arrayBlockingQueue.offer(e, timeout, unit);
    }
 
    // method used to get head of queue.Return NULL in case
    // of empty queue.
    public E peek() { return arrayBlockingQueue.peek(); }
 
    // method used to remove head of the queue.Returns NULL
    // if queue is empty else returns removed element.
    public E poll() { return arrayBlockingQueue.poll(); }
 
    // method used to remove head of this queue, waiting up
    // to the specified wait time if necessary for an
    // element to become available
    public E poll(long timeout, TimeUnit unit)
        throws InterruptedException
    {
        return arrayBlockingQueue.poll(timeout, unit);
    }
 
    // method used to inserts the specified element at
    // queue's tail.
    public void put(E e) throws InterruptedException
    {
        arrayBlockingQueue.put(e);
    }
 
    // method used to return number of additional elements
    // that the queue can have without blocking.
    public int remainingCapacity()
    {
        return arrayBlockingQueue.remainingCapacity();
    }
 
    // method used to remove single instance of the
    // specified element from this queue
    public boolean remove(Object o)
    {
        return arrayBlockingQueue.remove(o);
    }
 
    // method used to return size of queue.
    public int size() { return arrayBlockingQueue.size(); }
 
    // method used remove head of queue.Return NULL if queue
    // is empty else return removed element.
    public E take() throws InterruptedException
    {
        return arrayBlockingQueue.take();
    }
 
    // method used to return an array of the elements in
    // this queue.
    public Object[] toArray()
    {
        return arrayBlockingQueue.toArray();
    }
 
    // method used to return an array of the elements in
    // this queue.
    public <T> T[] toArray(T[] a)
    {
        return arrayBlockingQueue.toArray(a);
    }
 
    // method used to return string representation queue.
    public String toString()
    {
        return arrayBlockingQueue.toString();
    }
 
    public static void main(String[] args)
    {
        // capacity of ArrayBlockingQueue
        int capacity_queue = 10;
 
        // fair value of queue.If fair value is if true then
        // queue accesses for threads blocked on insertion or
        // removal, are processed in FIFO order if false then
        // access order is unspecified.
        boolean fair = true;
 
        // create object of ArrayBlockingQueue
        ArrayBlockingQueue<String> queue
            = new ArrayBlockingQueue<String>(capacity_queue,
                                             fair);
 
        // add  element to the queue
        queue.add("one");
        queue.add("two");
        queue.add("three");
        queue.add("four");
        queue.add("five");
 
        // print queue
        System.out.println(
            "ArrayBlockingQueue (when fair policy is true):"
            + queue);
 
        // print head element of queue
        System.out.println("Peek element of the queue : "
                           + queue.peek());
 
        // delete the specified element from the queue
        System.out.println(
            "Deleting the element 'five' from the queue : "
            + queue.remove("five"));
 
        // print queue
        System.out.println("ArrayBlockingQueue :" + queue);
 
        // clear the queue
        queue.clear();
 
        // print queue
        System.out.println(
            "ArrayBlockingQueue after clear operation :"
            + queue);
    }
}


Output

ArrayBlockingQueue (when fair policy is true):[one, two, three, four, five]
Peek element of the queue : one
Deleting the element 'five' from the queue : true
ArrayBlockingQueue :[one, two, three, four]
ArrayBlockingQueue after clear operation :[]

 



Last Updated : 05 Oct, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads