CKTIS / Java
LinkedBlockingQueue constructors: default and explicit capacity
Compare the no-argument constructor with the constructor that takes a capacity. Learn what `Integer.MAX_VALUE` means and what `offer(E)` does when a queue with capacity 2 is full.
Version: Java SE 21
Syntax
import java.util.concurrent.LinkedBlockingQueue;
// Constructor declarations in LinkedBlockingQueue<E>:
public LinkedBlockingQueue()
public LinkedBlockingQueue(int capacity)
// Example calls:
new LinkedBlockingQueue<String>()
new LinkedBlockingQueue<String>(2)In Java SE 21, both constructors covered here for java.util.concurrent.LinkedBlockingQueue<E> create an empty queue. LinkedBlockingQueue() sets its capacity to Integer.MAX_VALUE (2,147,483,647 elements). LinkedBlockingQueue(int) sets a fixed capacity from the capacity argument. The argument must be positive; zero or a negative value throws IllegalArgumentException.
Capacity limits the number of elements; it does not reserve memory. Linked nodes are allocated as elements are inserted, so the heap can run out long before the default limit is reached. An explicit bound such as 2 limits how many elements can be waiting in the queue, not how many bytes they use.
When the queue is full, offer(E) returns false without waiting for space, while put(E) waits for space and can throw InterruptedException if interrupted while waiting. remainingCapacity() reports the capacity minus the current element count, but it does not reserve a slot: another thread can change the queue before the next insertion attempt.
Examples
import java.util.concurrent.LinkedBlockingQueue;
public class Main {
public static void main(String[] args) {
LinkedBlockingQueue<String> defaultQueue = new LinkedBlockingQueue<>();
LinkedBlockingQueue<String> boundedQueue = new LinkedBlockingQueue<>(2);
System.out.println(defaultQueue.remainingCapacity());
System.out.println(boundedQueue.remainingCapacity());
System.out.println(boundedQueue.offer("A"));
System.out.println(boundedQueue.offer("B"));
System.out.println(boundedQueue.offer("C"));
System.out.println(boundedQueue.remainingCapacity());
}
}Result
2147483647 2 true true false 0
The first two lines show the available slots in the empty queues. `A` and `B` fit in the queue with capacity `2`, but `offer("C")` returns `false`. The final `0` means no slots remain.
Related lessons
- Java · Lesson 37 · Advanced · Version: 2