Understanding Java ArrayBlockingQueue: A Thread‑Safe Bounded Blocking Queue
This article explains the design, thread‑safety mechanisms, internal data structures, and core methods of Java's ArrayBlockingQueue, illustrating its creation, insertion, removal, and iteration with detailed code examples and a practical multithreaded demo.
ArrayBlockingQueue is a thread‑safe, bounded blocking queue implemented with an array, providing FIFO ordering and mutual‑exclusion via a ReentrantLock and two Condition objects (notEmpty and notFull) to coordinate producers and consumers.
Key characteristics
Implements BlockingQueue and extends AbstractQueue.
Uses an Object[] array as the underlying storage; the array size is fixed at construction time.
Combines a ReentrantLock (fair or non‑fair) with Condition objects to block threads when the queue is empty or full.
Core API (excerpt)
public ArrayBlockingQueue(int capacity)
public ArrayBlockingQueue(int capacity, boolean fair)
public boolean add(E e)
public boolean offer(E e)
public E take() throws InterruptedException
public Iterator<E> iterator()
// ... other methods such as clear(), contains(Object o), size(), etc.Construction
public ArrayBlockingQueue(int capacity, boolean fair) {
if (capacity <= 0)
throw new IllegalArgumentException();
this.items = new Object[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}The array items holds the queued elements, while takeIndex, putIndex, and count track the next element to remove, the next position to insert, and the current number of elements respectively.
Insertion (offer)
public boolean offer(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
if (count == items.length)
return false; // queue full
insert(e);
return true;
} finally {
lock.unlock();
}
}The private insert method stores the element, advances putIndex, increments count, and signals notEmpty to wake waiting consumers.
Removal (take)
public E take() throws InterruptedException {
final ReentrantLock lock = this.lock;
lock.lockInterruptibly();
try {
while (count == 0)
notEmpty.await();
return extract();
} finally {
lock.unlock();
}
} extractretrieves the element at takeIndex, nulls the slot for GC, advances takeIndex, decrements count, and signals notFull to wake waiting producers.
Iteration
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
// fields: remaining, nextIndex, nextItem, lastItem, lastRet
// constructor acquires lock, snapshots current state
// hasNext(), next(), and remove() are implemented with careful lock handling
}The iterator captures a snapshot of the queue size and iterates over the underlying array while respecting concurrent modifications.
Example usage
import java.util.*;
import java.util.concurrent.*;
public class ArrayBlockingQueueDemo1 {
private static Queue<String> queue = new ArrayBlockingQueue<>(20);
public static void main(String[] args) {
new MyThread("ta").start();
new MyThread("tb").start();
}
private static void printAll() {
for (String v : queue) System.out.print(v + ", ");
System.out.println();
}
private static class MyThread extends Thread {
MyThread(String name) { super(name); }
public void run() {
for (int i = 1; i <= 6; i++) {
String val = getName() + i;
queue.add(val);
printAll();
}
}
}
}Running the demo shows interleaved output from the two threads, confirming that ArrayBlockingQueue safely handles concurrent adds and iteration, whereas replacing the queue with a non‑thread‑safe LinkedList would cause a ConcurrentModificationException.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Big Data Technology & Architecture
Wang Zhiwu, a big data expert, dedicated to sharing big data technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
