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

Design

Which classes, and which rule belongs to whom

The point: three classes and one condition. Everything that two threads touch lives in the pool, behind one lock.

Decide

Is this a class at all?

CandidateClass?Why
PoolYesOwns the queue, the workers, the closed flag and their rules
JobYesCode, arguments and future belong together while they wait
WorkerA method at firstIt is a loop. A class if it needs its own state, such as a deque
QueueA list inside the poolThe rule closed plus full spans both, so one lock must cover both
FutureFrom the libraryBuilding it again is another page
PolicyLaterAs soon as there are two answers to a full queue
A library BlockingQueue is fine in real code. In the interview a list and a condition show that you know what is inside.

What we will write

TaskPool- jobs: deque<Job>- limit: int- closed: bool- threads: List<Thread>+ submit(fn, args): Future+ shutdown(wait)+ shutdownNow(): int- work()Caller+ submit, then get

1/3One object to call

Four public things: submit, two ways to close, and the number of workers at the start.

usesowns (dies together)depends on

Guard

What the lock protects

RuleFieldsBroken if
Never more than limit waitingjobs, limitTwo callers check the length together
Nothing is accepted after closingclosed, jobsThe flag is checked, then the pool closes, then the job is put
Each job is taken oncejobsTwo workers see the same first job
A worker leaves only when nothing is leftclosed, jobsIt checks the flag first and forgets the queue
The second row is the bug in many pools: a volatile flag and a separate queue. A job slips in after the last worker has left, and its future never ends.

The job that slipped in

Check and put must be one step under the same lock that sets the flag.