CKTIS / Java
ArrayBlockingQueue — a fixed-capacity blocking queue
ArrayBlockingQueue is a thread-safe FIFO queue backed by a fixed-capacity array. It transfers elements between producers and consumers and lets callers choose between waiting and receiving an immediate operation result.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
new ArrayBlockingQueue<E>(capacity)java.util.concurrent.ArrayBlockingQueue<E> implements BlockingQueue<E>. It stores elements in an array and retrieves them in FIFO order: the earliest inserted element is retrieved first. The ArrayBlockingQueue(int) constructor creates an empty queue with an unchangeable capacity; it throws IllegalArgumentException for capacity < 1.
put(e) waits for space in a full queue, while take() waits for an element in an empty queue. offer(e) and poll() do not wait for space or elements: they return false when full and null when empty, respectively. add(e) throws IllegalStateException when full. Timed offer and poll variants limit waiting. Waiting methods can throw InterruptedException; do not ignore interruption.
The queue rejects null: attempting to insert it throws NullPointerException. Thread safety of individual operations does not make a check-then-act sequence atomic; use the result of offer(e) instead of checking fullness before insertion.
FIFO element order does not imply fair service for waiting threads. The one-argument constructor does not guarantee their order; ArrayBlockingQueue(int, boolean) with true enables FIFO service for waiting threads. This entry describes Java SE 21; neither the repository runtime nor the production runtime has been attested.
Examples
import java.util.concurrent.ArrayBlockingQueue;
public class Main {
public static void main(String[] args) throws InterruptedException {
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(2);
queue.put("A");
queue.put("B");
System.out.println(queue.offer("C"));
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.poll());
}
}Result
false A B null
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.