ConcurrentLinkedQueue
A thread-safe, non-blocking queue.
Available since: Java 1.5
Syntax
public class ConcurrentLinkedQueue<E> implements Queue<E>Examples
A queue filled by several threads:
void main() {
var queue = new ConcurrentLinkedQueue<String>();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 50; i++) {
int n = i;
executor.submit(() -> queue.offer("event-" + n));
}
}
IO.println(queue.size());
IO.println(queue.contains("event-49"));
}Output:
50
trueNotes
poll() on an empty queue returns null without waiting for elements. If a consumer must wait for new elements, use a BlockingQueue (LinkedBlockingQueue, ArrayBlockingQueue) with put() and take(). For lists that are read often and changed rarely there is CopyOnWriteArrayList.
See also
- ConcurrentHashMap — A thread-safe map for concurrent use from many threads.
- Queue — A queue: elements are added at the tail and taken from the head.
- ArrayDeque — A fast array-based double-ended queue — a replacement for `Stack` and `LinkedList`.
In the tutorial
- Concurrent collections — Collections for multithreaded code in Java — ConcurrentHashMap and merge, CopyOnWriteArrayList, BlockingQueue and the producer-consumer pattern.