Video in progress
For producer-consumer, which do you choose: ArrayBlockingQueue or LinkedBlockingQueue?
ArrayBlockingQueue is always bounded, with a preallocated array and a single lock. LinkedBlockingQueue has separate locks for put and take, so producers and consumers collide less, but if it is created unbounded it can eat all your memory.
📖 Answer
The biggest trap is the default constructor:
BlockingQueue<Job> q = new LinkedBlockingQueue<>(); // capacity is Integer.MAX_VALUE
If the consumer slows down, the queue grows without limit and you end up with an OutOfMemoryError. Executors.newFixedThreadPool has exactly this unbounded queue inside, which is the classic reason tasks pile up on prod.
I always set a bound and decide myself what happens when it is full:
BlockingQueue<Job> q = new ArrayBlockingQueue<>(10_000);
// producer
if (!q.offer(job, 50, TimeUnit.MILLISECONDS)) {
metrics.increment("jobs.rejected"); // backpressure: reject, or slow the caller down
}
// consumer
Job j = q.take(); // waits if it is empty
How to choose:
ArrayBlockingQueue: memory is known up front, no new node per element, less load on the GC; withfair = truethe thread queue is fair (but slower).LinkedBlockingQueue(capacity): often better at high throughput thanks to two locks; a node is created for every element.- Others:
SynchronousQueue(no buffer, direct handoff),PriorityBlockingQueue(unbounded!),DelayQueue(delayed tasks).
For monitoring, export the queue size (q.size()) as a metric. If it keeps growing, that is the first sign you don't have enough consumers.
Sign up to mark studied questions and save your progress.