CKTIS / Java
LinkedBlockingQueue — a blocking FIFO queue
LinkedBlockingQueue is a thread-safe FIFO queue built from linked nodes. It supports an optional capacity bound and operations that wait for space or an element, making it useful for producer–consumer communication.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
LinkedBlockingQueue<E> queue = new LinkedBlockingQueue<>(capacity);java.util.concurrent.LinkedBlockingQueue<E> implements BlockingQueue<E>. Elements enter at the tail and are retrieved from the head in FIFO order. The queue supports multiple producers and consumers; do not confuse it with the non-blocking ConcurrentLinkedQueue.
new LinkedBlockingQueue<>(capacity) sets a positive capacity; a nonpositive value causes IllegalArgumentException. The no-argument constructor uses Integer.MAX_VALUE, not a practical memory-usage limit. An explicit bound helps limit the accumulation of pending work.
put(e) waits for space, while take() waits for an element. Both methods can throw InterruptedException. offer(e) returns false when the queue is full; poll() returns null when it is empty. In JDK 21, the timeout in the timed overloads of offer and poll applies to waiting for space and for an element, respectively, not to the entire call. Acquiring and reacquiring the internal lock can make the call take longer than the specified timeout. Elements cannot be null.
Thread safety of individual operations does not make a check-then-act sequence atomic: a remainingCapacity() result can become outdated before insertion. Use the operation's own result instead. The queue has no built-in close operation; terminating consumers requires a separate protocol.
Examples
import java.util.concurrent.LinkedBlockingQueue;
public class Main {
public static void main(String[] args) throws InterruptedException {
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(2);
queue.put("A");
queue.put("B");
System.out.println(queue.offer("C"));
System.out.println(queue.take());
System.out.println(queue.take());
System.out.println(queue.poll());
}
}Result
false A B null
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.