Java Creating ArrayBlockingQueue

Java Creating ArrayBlockingQueue

An ArrayBlockingQueue is a blocking queue that is implemented using an array in Java. It is a type of BlockingQueue that is designed for use in multi-threaded environments, and it provides blocking operations for inserting and removing elements from the queue.

Here is an example of how to create an ArrayBlockingQueue in Java:

import java.util.concurrent.ArrayBlockingQueue;

public class Main {
  public static void main(String[] args) {
    // Create an ArrayBlockingQueue with a capacity of 10
    ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(10);

    // Add elements to the ArrayBlockingQueue
    queue.add("Apple");
    queue.add("Banana");
    queue.add("Cherry");
    queue.add("Date");
    queue.add("Elderberry");

    // Print the ArrayBlockingQueue
    System.out.println(queue);  // Output: [Apple, Banana, Cherry, Date, Elderberry]
  }
}
Source:w‮.ww‬lautturi.com

In this example, we create an ArrayBlockingQueue with a capacity of 10 and add some elements to it. The ArrayBlockingQueue stores the elements in the order in which they were added.

If you try to add an element to the ArrayBlockingQueue when it is full, the add method will block until there is space available in the queue. Similarly, if you try to remove an element from the ArrayBlockingQueue when it is empty, the remove method will block until an element becomes available.

You can also create an ArrayBlockingQueue with a custom ReentrantLock and Condition object, which can be used to control the blocking behavior of the queue. Here is an example:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
  public static void main(String[] args) {
    // Create a ReentrantLock and a Condition object
    ReentrantLock lock = new ReentrantLock();
    Condition notFull = lock.newCondition();
    Condition notEmpty = lock.newCondition();

    // Create an ArrayBlockingQueue with a capacity of 10 and the custom lock and condition objects
    ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(10, true, lock, notFull, notEmpty);

    // Add elements to the ArrayBlockingQueue
    queue.add("Apple");
    queue.add("Banana");
    queue.add("Cherry");
    queue.add("Date");
    queue.add("Elderberry");

    // Print the ArrayBlockingQueue
    System.out.println(queue);  // Output: [Apple, Banana, Cherry, Date, Elderberry]

    // Try to add an element to the ArrayBlockingQueue
    try {
      queue.offer("Fig", 1, TimeUnit.SECONDS);
      System.out.println(queue);  // Output: [Apple, Banana, Cherry, Date, Elderberry, Fig]
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}
Created Time:2017-11-03 00:14:39  Author:lautturi