Thread pool
medium 70 minA 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?
| Candidate | Class? | Why |
|---|---|---|
| Pool | Yes | Owns the queue, the workers, the closed flag and their rules |
| Job | Yes | Code, arguments and future belong together while they wait |
| Worker | A method at first | It is a loop. A class if it needs its own state, such as a deque |
| Queue | A list inside the pool | The rule closed plus full spans both, so one lock must cover both |
| Future | From the library | Building it again is another page |
| Policy | Later | As soon as there are two answers to a full queue |
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
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
| Rule | Fields | Broken if |
|---|---|---|
| Never more than limit waiting | jobs, limit | Two callers check the length together |
| Nothing is accepted after closing | closed, jobs | The flag is checked, then the pool closes, then the job is put |
| Each job is taken once | jobs | Two workers see the same first job |
| A worker leaves only when nothing is left | closed, jobs | It checks the flag first and forgets the queue |
The job that slipped in