In the following code snippet you will learn how to use the LinkedBlockingQueue
class. This class implements the BlockingQueue
interface. We can create a bounded queue by specifying the queue capacity at the object construction. If we do not define the capacity, the upper bound is limited to the size of Integer.MAX_VALUE
.
The data in the queue represented as a linked node in a FIFO (First-In-First-Out) order. The head element of the queue is the longest element placed in the queue and the tail element is the latest element added to the queue.
Let’s see the code in action below:
package org.kodejava.util.concurrent;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class LinkedBlockingQueueExample {
public static void main(String[] args) {
final BlockingQueue<String> queue = new LinkedBlockingQueue<>(1024);
// Producer Tread
new Thread(() -> {
while (true) {
try {
String data = UUID.randomUUID().toString();
System.out.printf("[%s] PUT [%s].%n",
Thread.currentThread().getName(), data);
queue.put(data);
Thread.sleep(250);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "Producer").start();
// Consumer-1 Thread
new Thread(() -> {
while (true) {
try {
String data = queue.take();
System.out.printf("[%s] GET [%s].%n",
Thread.currentThread().getName(), data);
Thread.sleep(550);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "Consumer-1").start();
// Consumer-2 Thread
new Thread(() -> {
while (true) {
try {
String data = queue.take();
System.out.printf("[%s] GET [%s].%n",
Thread.currentThread().getName(), data);
Thread.sleep(750);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "Consumer-2").start();
}
}
The output of the code snippet above:
[Producer] PUT [34418601-19cf-41fc-aecc-a0fa7caa72bb].
[Consumer-1] GET [34418601-19cf-41fc-aecc-a0fa7caa72bb].
[Producer] PUT [f2050eaa-c575-4faf-89e8-1ad0e3fbce0e].
[Consumer-2] GET [f2050eaa-c575-4faf-89e8-1ad0e3fbce0e].
[Producer] PUT [2f24985b-009b-44c3-9cec-7a066aa08ecf].
[Consumer-1] GET [2f24985b-009b-44c3-9cec-7a066aa08ecf].
[Producer] PUT [b4332823-c1a2-4587-bf5f-1f67407d6945].
[Consumer-2] GET [b4332823-c1a2-4587-bf5f-1f67407d6945].
[Producer] PUT [33edcd78-1b14-4913-afe2-7f44d76db50b].
[Consumer-1] GET [33edcd78-1b14-4913-afe2-7f44d76db50b].
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024