ConcurrentLinkedQueue in Java is a concurrent, unbounded queue implementation that provides thread-safe operations for high-performance, scalable handling of elements in a FIFO (First-In-First-Out) manner. It is part of the java.util.concurrent package and is designed for scenarios where multiple threads need to access a queue concurrently without explicit synchronization.
The syntax for creating a ConcurrentLinkedQueue is straightforward:
ConcurrentLinkedQueue<E> queue = new ConcurrentLinkedQueue<>();
Here, E represents the type of elements stored in the queue.Code language: HTML, XML (xml)
import java.util.concurrent.ConcurrentLinkedQueue;
public class ConcurrentLinkedQueueExample {
public static void main(String[] args) {
ConcurrentLinkedQueue<Integer> queue = new ConcurrentLinkedQueue<>();
// Producer thread adding elements to the queue
Thread producer = new Thread(() -> {
for (int i = 1; i <= 10; i++) {
queue.offer(i);
System.out.println("Produced: " + i);
try {
Thread.sleep(500); // Simulate some processing time
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Consumer thread removing elements from the queue
Thread consumer = new Thread(() -> {
while (!queue.isEmpty()) {
Integer element = queue.poll();
System.out.println("Consumed: " + element);
try {
Thread.sleep(1000); // Simulate some processing time
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
// Start producer and consumer threads
producer.start();
consumer.start();
// Wait for threads to finish
try {
producer.join();
consumer.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Queue is empty: " + queue.isEmpty());
}
}
/*
D:\javaplanet\Collection Framework>javac ConcurrentLinkedQueueExample.java
D:\javaplanet\Collection Framework>java ConcurrentLinkedQueueExample
Produced: 1
Produced: 2
Produced: 3
Produced: 4
Produced: 5
Produced: 6
Produced: 7
Produced: 8
Produced: 9
Produced: 10
Queue is empty: false
*/Benefits of ConcurrentLinkedQueue
- Concurrency: Supports concurrent access by multiple threads for both add (producer) and remove (consumer) operations efficiently.
- Performance: Offers high throughput and scalability, suitable for applications with high contention and dynamic workload.
- Non-blocking Operations: Operations are non-blocking and do not cause threads to wait, enhancing overall performance.
- No Fixed Size Limit: Can grow dynamically based on the number of elements added, making it versatile for various use cases.
In summary, ConcurrentLinkedQueue is an efficient choice for managing concurrent access to a FIFO queue in Java applications. It offers thread-safe operations, high throughput, and scalability, making it suitable for scenarios where multiple threads need to produce and consume elements concurrently without performance degradation or blocking issues.
