AlgoViz

Thread pool

medium 70 min

A few threads that live long, one queue with a limit, and a loop: take, run, repeat.

Watch lesson5:06

Growing

Core, maximum, queue: the surprising order

The point: in Java's ThreadPoolExecutor a new task first gets a core worker, then a place in the queue, and only then an extra worker. Many people expect the last two the other way round.

Where does a new task go?

With a queue without a limit the answer in the middle is always yes. So the maximum is never used, whatever you write there.

The growth rule as a pure function

The whole decision without any thread. So it can be tested with a table.

from dataclasses import dataclass@dataclass(frozen=True)class Rules:    core: int           # workers we keep    most: int           # workers we allow in a rush    places: int         # queue length    keep_alive: float   # seconds an extra worker may idledef admit(running, queued, r):    if running < r.core:        return "new worker"    if queued < r.places:        return "queue"    if running < r.most:        return "new worker"    return "reject"

Lines 4 to 8

Four numbers that only make sense together, so they travel together and cannot change halfway.

1 of 4

Why it is built this way

  • Python's ThreadPoolExecutor is simpler: no queue limit, and since 3.8 it reuses an idle worker before it starts another one.

Same nine tasks, other settings

Core, most, placesStarted at onceWaitingRefused
2, 4, 3432
2, 4, no limit270
0, no limit, 0 (cached)900
4, 4, 3 (fixed)432
4, 4, 0 (direct)405
Second row: the maximum of 4 does nothing. Recommended default: core equal to maximum, a bounded queue, a chosen policy. Core workers may also be allowed to leave, with allowCoreThreadTimeOut(true).

You want extra workers before tasks have to wait. How?

BreaksRaise the maximum
How
From 16 to 64, with an unbounded queue.
Limit
Nothing changes. The queue never says full.
Choose when
Never.
WorksCore equal to maximum
How
A fixed pool with idle core workers allowed to leave.
Limit
It starts a new worker for each task until the core is reached.
Choose when
The usual answer.
StrongA queue that says full early
How
Its offer answers false while running is below the maximum, and the refusal handler puts the task into the queue. Tomcat's own task queue refuses in this way.
Limit
It must know the pool, and a race between two submits must be thought through.
Choose when
Servers with uneven load.

Adapt

Pools that measure

The .NET pool creates threads freely up to a minimum. Beyond that it may create more or wait for tasks to finish, and it creates and destroys threads in order to improve throughput, the number of tasks finished per time. The idea: try one more, see if more is done, otherwise go back. A pool like this finds the bottleneck without knowing its name. Blocking tasks confuse it, since nothing finishes.