Thread pool
medium 70 minA 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?
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.
Why it is built this way
- Python's
ThreadPoolExecutoris 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, places | Started at once | Waiting | Refused |
|---|---|---|---|
| 2, 4, 3 | 4 | 3 | 2 |
| 2, 4, no limit | 2 | 7 | 0 |
| 0, no limit, 0 (cached) | 9 | 0 | 0 |
| 4, 4, 3 (fixed) | 4 | 3 | 2 |
| 4, 4, 0 (direct) | 4 | 0 | 5 |
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
offeranswers 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.