Java ArrayBlockingQueue

ArrayBlockingQueue class is a bounded blocking queue backed by an array. By bounded, it means that the size of the Queue is fixed. Once created, the capacity cannot be changed. Attempts to put an element into a full queue will result in the operation blocking. Similarly attempts to take an element from an empty queue will also be blocked. Boundness of the ArrayBlockingQueue can be achieved initially bypassing capacity as the parameter in the constructor of ArrayBlockingQueue. This queue orders elements FIFO (first-in-first-out). It means that the head of this queue is the oldest element of the elements present in this queue.

Creating ArrayBlockingQueue

In order to create an array blocking queue, we must import the java.util.concurrent.ArrayBlockingQueue package.


                    // Creating String type ArrayBlockingQueue with size 5
                    ArrayBlockingQueue<String> animals = new ArrayBlockingQueue<>(5);

                    // Creating Integer type ArrayBlockingQueue with size 5
                    ArrayBlockingQueue<Integer> age = new ArrayBlockingQueue<>(5);
                  
Why use ArrayBlockingQueue?

The ArrayBlockingQueue uses arrays as its internal storage. It is considered as a thread-safe collection. Hence, it is generally used in multi-threading applications. Suppose, one thread is inserting elements to the queue and another thread is removing elements from the queue. Now, if the first thread is slower than the second thread, then the array blocking queue can make the second thread waits until the first thread completes its operations.

ArrayBlockingQueue constructos

In order to create a ArrayBlockingQueue, we need to create an object of the ArrayBlockingQueue class. The ArrayBlockingQueue class consists of various constructors that allow the possible creation of the ArrayBlockingQueue. The following are the constructors available in this class.

Constructor Description Example
ArrayBlockingQueue(int capacity) Creates an ArrayBlockingQueue with the given (fixed) capacity and default access policy. ArrayBlockingQueue abq = new ArrayBlockingQueue(int capacity);
ArrayBlockingQueue(int capacity, boolean fair) Creates an ArrayBlockingQueue with the given (fixed) capacity and the specified access policy. If the fair value is if true then queue accesses for threads blocked on insertion or removal, are processed in FIFO order; if false the access order is unspecified. ArrayBlockingQueue abq = new ArrayBlockingQueue(int capacity, boolean fair);
ArrayBlockingQueue(int capacity, boolean fair, Collection c) Creates an ArrayBlockingQueue with the given (fixed) capacity, the specified access policy and initially containing the elements of the given collection, added in traversal order of the collection’s iterator. If the fair value is if true then queue accesses for threads blocked on insertion or removal, are processed in FIFO order; if false the access order is unspecified. ArrayBlockingQueue abq = new ArrayBlockingQueue(int capacity, boolean fair, Collection c);
Methods of ArrayBlockingQueue

The ArrayBlockingQueue class provides the implementation of all the methods in the BlockingQueue interface.

Method Name Description
add() Inserts the specified element to the array blocking queue. It throws an exception if the queue is full.
offer() Inserts the specified element to the array blocking queue. It returns false if the queue is full.
peek() Returns an element from the front of the array blocking queue. It returns null if the queue is empty.
offer() inserts the specified element at the end of the array deque.
remove() Returns and removes a specified element from the array blocking queue. It throws an exception if the queue is empty.
poll() Returns and removes a specified element from the array blocking queue. It returns null if the queue is empty.
clear() Removes all the elements from the array blocking queue.
put() To add an element to the end of an array blocking queue, we can use the put() method.
take() To return and remove an element from the front of the array blocking queue, we can use the take() method.
contains(element) Searches the array blocking queue for the specified element.If the element is found, it returns true, if not it returns false.
size() Returns the length of the array blocking queue.
toArray() Converts array blocking queue to an array and returns it.
toString() Converts the array blocking queue to string
Basic Operations on ArrayBlockingQueue

The ArrayBlockingQueue class provides various methods to perform different operations on ArrayBlockingQueue. We will look at some commonly used ArrayBlockingQueue operations.

  1. ▪ Insert Elements
  2. ▪ Access Elements
  3. ▪ Remove Elements

Insert Elements

                        import java.util.concurrent.ArrayBlockingQueue;

                        class Main {
                            public static void main(String[] args) {
                                ArrayBlockingQueue<String> animals = new ArrayBlockingQueue<>(5);

                                // Using add()
                                animals.add("Dog");
                                animals.add("Cat");

                                // Using offer()
                                animals.offer("Horse");
                                System.out.println("ArrayBlockingQueue: " + animals);
                            }
                        }

                    
Access Elements

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

                        class Main {
                            public static void main(String[] args) {
                                ArrayBlockingQueue<String> animals = new ArrayBlockingQueue<>(5);

                                // Add elements
                                animals.add("Dog");
                                animals.add("Cat");
                                animals.add("Horse");
                                System.out.println("ArrayBlockingQueue: " + animals);

                                // Using peek()
                                String element = animals.peek();
                                System.out.println("Accessed Element: " + element);

                                // Using iterator()
                                Iterator<String> iterate = animals.iterator();
                                System.out.print("ArrayBlockingQueue Elements: ");

                                while(iterate.hasNext()) {
                                    System.out.print(iterate.next());
                                    System.out.print(", ");
                                }

                                // for each loop
                                for(String str: animals) {
                                  System.out.println(str);
                                }
                            }
                        }
                    
Remove Elements

                        import java.util.concurrent.ArrayBlockingQueue;

                        class Main {
                            public static void main(String[] args) {
                                ArrayBlockingQueue<String> animals = new ArrayBlockingQueue<>(5);

                                animals.add("Dog");
                                animals.add("Cat");
                                animals.add("Horse");
                                System.out.println("ArrayBlockingQueue: " + animals);

                                // Using remove()
                                String element1 = animals.remove();
                                System.out.println("Removed Element:");
                                System.out.println("Using remove(): " + element1);

                                // Using poll()
                                String element2 = animals.poll();
                                System.out.println("Using poll(): " + element2);

                                // Using clear()
                                animals.clear();
                                System.out.println("Updated ArrayBlockingQueue: " + animals);
                            }
                        }
                    
put() and take() Method

                        import java.util.concurrent.ArrayBlockingQueue;

                        class Main {
                            public static void main(String[] args) {
                                ArrayBlockingQueue<String> animals = new ArrayBlockingQueue<>(5);

                            try {
                                // Add elements to animals
                                animals.put("Dog");
                                animals.put("Cat");
                                System.out.println("ArrayBlockingQueue: " + animals);
                                }
                                catch(Exception e) {
                                    System.out.println(e);
                                }
                            }

                            try {
                                //Add elements to animals
                                animals.put("Dog");
                                animals.put("Cat");
                                System.out.println("ArrayBlockingQueue: " + animals);
                     
                                // Remove an element
                                String element = animals.take();
                                System.out.println("Removed Element: " + element);
                             }
                             catch(Exception e) {
                                 System.out.println(e);
                             }
                        }