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 build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023
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.