ArrayBlockingQueue
is one implementation of the java.util.concurrent.BlockingQueue
which internally store the queue elements inside an array. The ArrayBlockingQueue
can store elements for the size defined when the object is initialized, by the constructor. Once it size is defined it cannot be change or resize.
The code snippet below demonstrate the ArrayBlockingQueue
class. We initialize the queue to allow its internal array to store maximum of 64 elements.
package org.kodejava.util.concurrent;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
public class ArrayBlockingQueueExample {
private final BlockingQueue<String> sharedQueue = new ArrayBlockingQueue<>(64);
public static void main(String[] args) {
new ArrayBlockingQueueExample().createProducerConsumer();
}
private void createProducerConsumer() {
new Thread(() -> {
while (true) {
System.out.println(Thread.currentThread().getName());
try {
sharedQueue.put("DATA-" + UUID.randomUUID());
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "Producer Thread").start();
new Thread(() -> {
while (true) {
System.out.print(Thread.currentThread().getName() + " => ");
try {
System.out.println(sharedQueue.take());
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "Consumer Thread-1").start();
}
}
Latest posts by Wayan (see all)
- How do I convert Map to JSON and vice versa using Jackson? - June 12, 2022
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022
ArrayBlockingQueue in Java orders elements FIFO (first-in-first-out). The head of the queue is the 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.