The Threads Were Idle, So Why Were Tasks Still Rejected?

When sporadic RejectedExecutionException alerts started firing in production, my first instinct was to check the thread pool config: 32 core threads, 32 max threads, queue capacity 16. The service submits work in batches and doesn’t send the next batch until the current one finishes. On paper, the pool had plenty of headroom. There was no reason it should be tripping the rejection policy.

Bumping up the queue size stopped the errors right away. But stopping the bleeding only proved the bug had something to do with “instantaneous capacity”; it didn’t explain what had actually happened. Only after tracing the whole path through the JDK source did it click: my mental model of corePoolSize + queueCapacity was way too static. That sum tells you the maximum number of in-flight tasks the pool can hold at a given instant. It never promised it could cleanly swallow every batch burst.

Adding a sleep between batches didn’t help at all

Strip away the business logic, and the skeleton of the code looked roughly like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
ThreadPoolExecutor pool = new ThreadPoolExecutor(
32, 32,
10, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(16)
);

for (int batch = 0; batch < 100; batch++) {
CountDownLatch done = new CountDownLatch(batchSize);
for (int i = 0; i < batchSize; i++) {
pool.execute(() -> {
try {
// do something
} finally {
done.countDown();
}
});
}
done.await();
}

With CountDownLatch gating the outer loop, the next batch can never start until the previous one finishes. The way I did the math back then, 32 threads plus 16 queue slots meant the pool could absorb 48 tasks at once. As long as each batch was well under 48, how could it ever fail?

My first suspect was the handoff between batches: maybe the previous batch had just called countDown(), and before the worker threads finished wrapping up and freeing themselves, the next batch slammed in? To test that, I put a sleep(100) between batches, then bumped it all the way up to 2 seconds. It still failed.

That ruled out leftover work from the previous batch and pointed straight to my real blind spot: that 2-second pause sat before the batch began. Once execution entered the inner for loop, the main thread still fired off dozens of execute() calls like a machine gun in a few microseconds.

Removing CountDownLatch made the failures even more random

Next I looked at CountDownLatch. Once I removed await(), the behavior got even weirder: sometimes several batches went through cleanly, other times it threw almost immediately. Shrinking batchSize lowered the failure rate, but never eliminated it.

That messier behavior gave away the real clue: the outcome depended heavily on OS thread scheduling. If a static parameter calculation were wrong, the code would fail deterministically at the exact same spot every time. A flaky “works sometimes, fails other times” symptom almost certainly meant a race on the timeline between the main thread pushing tasks into the queue and worker threads pulling them out.

Looking back, CountDownLatch did very little here. It only guaranteed “wait until the previous batch drains before starting the next.” It had zero control over how fast the main thread stuffed tasks into the pool within a single batch. Even if the previous batch finished completely, a sudden burst of submissions could still overflow a 16-slot queue on the spot.

Even when every core thread is idle, new tasks still go into the queue first

To watch every enqueue step up close locally, I shrank the pool down to the bare minimum: 2 core threads, 2 max threads, queue size 1, and stepped through ThreadPoolExecutor.execute() in a debugger.

Its core logic is just three steps:

  1. If the current worker count (workerCount) is less than corePoolSize, spin up a new core thread and hand it the task directly.
  2. If the worker count is already at corePoolSize, call workQueue.offer() to try putting the task into the queue.
  3. If the queue is full too, try creating a non-core thread; if we’ve already hit maximumPoolSize, immediately invoke the rejection policy.

One detail that’s easy to miss when reading this code casually: Step 1 checks how many workers exist in the pool, not how many are currently busy.

Once the pool has warmed up, even if all 32 core threads are sitting around idle waiting for work, workerCount is still a solid 32. When the main thread submits a new task, Step 1 is skipped altogether. The submitting thread never hands a task directly to an idle worker. It has to go through Step 2, drop the task into workQueue, and wait for a worker blocked on take() to wake up and claim it.

And in a fixed-size pool where corePoolSize == maximumPoolSize, the instant Step 2’s offer() returns false, Step 3 has zero room to expand, and the default AbortPolicy throws RejectedExecutionException on the spot.

A queue of size 1 exposes those few microseconds

With the queue shrunk to 1, here is the crash in slow motion:

1
2
3
4
5
6
7
8
9
10
11
The pool already has 2 worker threads, both completely idle and waiting for work
↓
Main thread submits Task A; offer() succeeds; queue is instantly full (1/1)
↓
A blocked worker is signaled, but the OS hasn't scheduled it onto a CPU yet
↓
Without pausing, the main thread submits Task B; offer() sees the queue is full
↓
Can't scale up (already at maximumPoolSize), so Task B is rejected on the spot
↓
A few microseconds later, the worker finally gets a CPU slice and lazily pulls Task A

Put plainly, ArrayBlockingQueue.offer() is strictly non-blocking: if there’s an open slot at that exact nanosecond it returns true; if not, it immediately returns false without waiting at all for a consumer to clear space. The worker threads really are trying to drain the queue via take(), but whether one gets scheduled on a CPU and pops an item before the main thread’s next offer() lands is completely up to the OS scheduler.

The queue is already full with the first task

Blaming this on producer/consumer “out-of-order execution” isn’t quite accurate. It’s completely normal timing contention in a standard concurrency model. The main thread has no obligation to pause and wait for workers to consume, and ThreadPoolExecutor deliberately uses non-blocking offer() so that when a queue fills up, it can immediately fall through to scaling up or rejecting, letting the caller know right away that the pool can’t keep up.

One more piece of the puzzle: if a single batch is strictly less than or equal to the queue capacity (say, queue size 16 and at most 16 tasks per batch), and the previous batch has truly drained, then even if every worker stays asleep and hasn’t popped a single task yet, all 16 tasks will still fit cleanly into the queue without throwing. So with the stripped-down snippet from the top of this post, setting batchSize <= 16 will not reproduce the exception. The reason production failed on 32/32/16 was that the burst submitted in one wave (or combined with other traffic sharing the same pool) exceeded those 16 queue slots. Only when “tasks submitted in a tight burst > remaining queue capacity” does that microsecond race for CPU slices actually kick off.

Growing the queue stops the bleeding, but don’t treat it as a cure-all

Expanding the queue from 16 to 160 built a much bigger reservoir: even if workers didn’t wake up right away, an entire batch thrown by the main thread could sit comfortably in the queue, and the errors vanished.

During debugging I also tried a hacky experiment: wrapping the queue so offer() spun or paused briefly to give workers a window to pull tasks. Sure enough, the errors disappeared in the test, but that’s just fooling yourself. Turning a non-blocking offer() into a half-blocking one just masks the issue by slowing down the main thread, which is asking for different trouble in production. Swap back to a standard ArrayBlockingQueue, and the exception came right back.

Even though increasing queue size put out this fire, you really shouldn’t tune queues by “bumping the number until alerts stop.” A deeper queue absorbs sharper bursts, sure, at the price of longer wait times (latency/RT) in the queue and higher memory usage. Setting it right means doing the full math across batch size, per-task execution time, and the maximum latency the business can tolerate.

If the caller can afford to slow down, there are two cleaner options: either slice batchSize smaller at the entry point, or switch the rejection handler to CallerRunsPolicy. With CallerRunsPolicy, once the queue fills up, the submitting thread runs the task itself, and while it’s busy doing that work, it naturally stops hammering the pool with new submissions. That gives you built-in backpressure. Of course, that assumes your calling thread can tolerate being blocked for a bit.

Looking back on what went wrong

Looking back, the thing that tripped me up most was that rigid mental formula: 32 + 16 = 48.

That total only holds at a very specific moment in time. Right after a cold start, the first 32 tasks really do trigger core thread creation, and tasks 33 through 48 land in the queue. But once the pool is warmed up and all 32 workers are alive, even if every single one of them is idle, new tasks still have to cross the single narrow bridge of the work queue first. At that point, whether you survive a tight burst loop depends less on those 32 threads and more on those 16 queue slots, plus how fast the OS scheduler hands out CPU slices.

So the next time a thread pool throws a rejection exception, don’t just stare at the three static numbers (corePoolSize, maximumPoolSize, queueCapacity). Look at poolSize, activeCount, queue depth, and the main thread’s submission rate at the exact moment the burst hits.

Growing the queue is really just trading space for time. It lets the system ride out a burst a little longer, without making the pool process work any faster. Next time you tweak these knobs, don’t stop once rejection counts drop to zero; check peak queue depth and end-to-end task latency too, so you don’t trade visible exceptions for hidden queuing across the whole pipeline.


References: ThreadPoolExecutor Documentation, ArrayBlockingQueue Documentation