Thread pool
medium 70 minA few threads that live long, one queue with a limit, and a loop: take, run, repeat.
Watch lesson5:06
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
Take, run, repeat: a few threads, one queue, one limit.
Shearing day: three shearers who stay, a pen with three places, a token for the wool. Or a kitchen with a fixed number of cooks and a board of order tickets: nobody is hired per dish. Or a taxi stand: cabs wait, carry a passenger and come back, and passengers queue when all are away.
Cheat sheet
- Parts
- pool, workers, queue, task, future
- Loop
- wait, take, unlock, run
- Compute
- cores + 1
- Wait
- cores x (1 + W/C)
- Busy workers
- tasks per second x seconds
- Queue length
- patience x tasks per second
- Java order
- core, queue, extra, reject
- Types
- fixed, cached, scheduled, stealing
- Cached
- idle threads end after 60 s
- Full
- refuse, caller runs, drop, wait
- Close
- shutdown, await, shutdownNow
- Never
- wait for a task of your own pool
Spot it when you see
- Many short tasks
- Background work with a result
- Implement an executor
- Bursts
Tricks that stick
- FCSS: fixed, cached, scheduled, stealing.
- Owner newest, thief oldest.
- A queue length is a time in disguise.
Do not forget
- A queue without a limit
- Running a task inside the lock
- Flag and queue under different locks
- Futures nobody reads
- Thread-locals left behind
- shutdown forgotten