Video in progress
When would you pick ArrayBlockingQueue, LinkedBlockingQueue or ConcurrentLinkedQueue?
If threads need to wait (producer-consumer), use a blocking queue: ArrayBlockingQueue for a strict capacity and few allocations, a bounded LinkedBlockingQueue for higher throughput. If nobody should wait or block, use the lock-free ConcurrentLinkedQueue.
📖 Answer
All three are thread-safe. The difference is their internal structure and how they behave when empty or full.
ArrayBlockingQueue |
LinkedBlockingQueue |
ConcurrentLinkedQueue |
|
|---|---|---|---|
| Capacity | fixed, required | optional (default Integer.MAX_VALUE) |
unbounded |
| Lock | one lock shared by put and take | two: putLock and takeLock |
no lock, CAS |
| Allocation | the array, once | a node per element | a node per element |
| When empty | take() waits |
take() waits |
poll() returns null right away |
In LinkedBlockingQueue, the producer and the consumer take different locks, so it's usually faster when both are active. ArrayBlockingQueue is stable in memory and gives the GC less work.
ConcurrentLinkedQueue has no mechanism to make a consumer wait. If poll() comes back empty, you end up spinning in a loop and burning CPU:
while (running) {
Task t = queue.poll();
if (t == null) continue; // busy-spin: 100% CPU
t.run();
}
That's why it's good for "many threads write, and someone collects the items from time to time" cases: for example, collecting audit records and flushing them from a scheduler. One more catch: its size() method is O(n), because it walks the whole list.
This is how I usually choose: for distributing work, a bounded LinkedBlockingQueue or ArrayBlockingQueue; for collecting where blocking isn't allowed, ConcurrentLinkedQueue. I leave an unbounded queue in prod only when it's clear that the read rate is higher than the write rate.
Sign up to mark studied questions and save your progress.