ArrayBlockingQueue Vs. Google Guava Non-Blocking EvictingQueue Example

Concurrency utilities are very amazing in Java.

java.util.concurrent package contains lots of utilities which we could use in number of different ways.

In this tutorial we will go over difference between  java.util.concurrent.ArrayBlockingQueue and com.google.common.collect.EvictingQueue.

What is EvictingQueue?

EvictingQueue is part of Google's Guava library. Which is a non-blocking, bounded (Fixed Size) queue that automatically removes elements from the head of the queue when attempting to add elements to a full queue.

How to add Google’s Guava library to your eclipse-java Project?

You could add below maven dependency to pom.xml file if you are using maven project. In case of non-maven project – you have to download it from here and include library into your project’s classpath.

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1.1-jre</version>
</dependency>

What is ArrayBlockingQueue?

It’s a blocking, bounded (Fixed Size) queue that stores the elements internally in an array. It CAN'T store unlimited amounts of elements. This queue orders elements FIFO (first-in-first-out).

Read more: Singleton Queue Example

Let’s get started on Example

  1. Create ArrayBlockingQueue with size 10
  2. Create EvictingQueue with size 10
  3. Try to add 15 elements to queue
  4. For EvictingQueue – it will not throw any error
  5. For ArrayBlockingQueue – it will throw Queue Full error

Create class CrunchifyArrayBlockingQueueVsEvictingQueue.java

package crunchify.com.tutorials;

import com.google.common.collect.EvictingQueue;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * @author Crunchify.com
 * ArrayBlockingQueue Vs. Google Guava Non-Blocking EvictingQueue Example
 *
 */

public class CrunchifyArrayBlockingQueueVsEvictingQueue {

        private static void CrunchifyArrayBlockingQueue() {
                
                // ArrayBlockingQueue: A bounded blocking queue backed by an array. This queue orders elements FIFO (first-in-first-out).
                // The head of the queue is that element that has been on the queue the longest time.
                // The tail of the queue is that element that has been on the queue the shortest time.
                // New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue.
                ArrayBlockingQueue<String> crunchifyQueue = new ArrayBlockingQueue<String>(
                                10);

                String crunchifyMsg = "This is ArrayBlockingQueue - by Crunchify";
                try {
                        // We are looping for 15 times - Error once queue full
                        for (int counter = 1; counter <= 15; counter++) {
                                
                                // add(): 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.
                                crunchifyQueue.add(crunchifyMsg + counter);
                                
                                // size(): Returns the number of elements in this queue.
                                crunchifyLog("ArrayBlockingQueue size: " + crunchifyQueue.size());
                        }
                } catch (Exception e) {
                        crunchifyLog("\nException Occurred: ");
                        e.printStackTrace();
                }

        }

        public static void main(String[] args) {

                // Test EvictingQueue with size 10
                CrunchifyEvictingQueue();

                crunchifyLog("\n============= New LINE ==============\n");

                // Test ArrayBlockingQueue with size 10
                CrunchifyArrayBlockingQueue();
        }

        private static void CrunchifyEvictingQueue() {
                // Queue: A collection designed for holding elements prior to processing. Besides basic Collection operations,
                // queues provide additional insertion, extraction, and inspection operations.
                // Each of these methods exists in two forms: one throws an exception if the operation fails,
                // the other returns a special value (either null or false, depending on the operation).
                Queue<String> crunchifyQueue = EvictingQueue.create(10);

                String crunchifyMsg = "This is EvictingQueue - by Crunchify";
                try {
                        // We are looping for 15 times - No error after queue full.
                        // Instead, it will remove element from queue in FIFO order
                        for (int i = 1; i <= 15; i++) {
                                
                                // add: Inserts the specified element into this queue if it is possible to do so immediately without violating capacity restrictions,
                                // returning true upon success and throwing an IllegalStateException if no space is currently available.
                                crunchifyQueue.add(crunchifyMsg + i);

                                crunchifyLog("EvictingQueue size: " + crunchifyQueue.size());
                        }
                } catch (Exception e) {
                        crunchifyLog("Exception Occurred: " + e);
                }

        }

        private static void crunchifyLog(String crunchifyText) {
                System.out.println(crunchifyText);

        }

}

Just run this Java Program as an application in Eclipse Console or IntelliJ IDEA and you will see result like this.

Console Result:

EvictingQueue size: 1
EvictingQueue size: 2
EvictingQueue size: 3
EvictingQueue size: 4
EvictingQueue size: 5
EvictingQueue size: 6
EvictingQueue size: 7
EvictingQueue size: 8
EvictingQueue size: 9
EvictingQueue size: 10
EvictingQueue size: 10
EvictingQueue size: 10
EvictingQueue size: 10
EvictingQueue size: 10
EvictingQueue size: 10

============= New LINE ==============

ArrayBlockingQueue size: 1
ArrayBlockingQueue size: 2
ArrayBlockingQueue size: 3
ArrayBlockingQueue size: 4
ArrayBlockingQueue size: 5
ArrayBlockingQueue size: 6
ArrayBlockingQueue size: 7
ArrayBlockingQueue size: 8
ArrayBlockingQueue size: 9
ArrayBlockingQueue size: 10

Exception Occurred: 
java.lang.IllegalStateException: Queue full
        at java.base/java.util.AbstractQueue.add(AbstractQueue.java:98)
        at java.base/java.util.concurrent.ArrayBlockingQueue.add(ArrayBlockingQueue.java:329)
        at crunchify.com.tutorials.CrunchifyArrayBlockingQueueVsEvictingQueue.CrunchifyArrayBlockingQueue(CrunchifyArrayBlockingQueueVsEvictingQueue.java:32)
        at crunchify.com.tutorials.CrunchifyArrayBlockingQueueVsEvictingQueue.main(CrunchifyArrayBlockingQueueVsEvictingQueue.java:52)

Process finished with exit code 0

Let me know if you face any issue running above program.

The post ArrayBlockingQueue Vs. Google Guava Non-Blocking EvictingQueue Example appeared first on Crunchify.