Video in progress

Choosing a queue for ThreadPoolExecutor: how do you decide between ArrayBlockingQueue, LinkedBlockingQueue and SynchronousQueue?

The queue type determines how the pool itself behaves: an unbounded LinkedBlockingQueue effectively disables max pool size and can fill up memory, a SynchronousQueue accepts a task only if there is a free thread, and a bounded ArrayBlockingQueue gives you backpressure.

📖 Answer

The ThreadPoolExecutor rule: if the core threads are busy, the task goes into the queue; only when the queue is full are new threads created (up to max); if those are full too, the rejection policy kicks in.

It follows that:

new LinkedBlockingQueue<>() is unbounded. The queue never fills up, so the pool never grows beyond core and maximumPoolSize means nothing. If a downstream service slows down, millions of tasks pile up in the queue and it ends in an OOM. Executors.newFixedThreadPool is built exactly like this.

SynchronousQueue has zero capacity, and every offer requires a thread waiting to take it. If there is no free thread, a new one is created. newCachedThreadPool is built this way, with max = Integer.MAX_VALUE. If load spikes, you get thousands of threads.

ArrayBlockingQueue(n) is a preallocated array with a single lock. It gives you a definite bound.

LinkedBlockingQueue(n) is the bounded variant, with separate locks for put and take. It is slightly better at very high concurrency, but allocates a node per element.

On prod I usually do this:

var pool = new ThreadPoolExecutor(
        16, 32, 60, TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(1_000),
        new ThreadPoolExecutor.CallerRunsPolicy()); // when full, the caller runs it itself and slows down

The queue size answers the question "how much delay can we tolerate?". If one task takes 50 ms and you have 16 threads, a queue of 1000 means about 3 seconds of waiting. Queue length and the rejection count should be in your metrics.