Thread pool
medium 70 minA few threads that live long, one queue with a limit, and a loop: take, run, repeat.
Watch lesson5:06
Closing
Deploys, stuck tasks, lost errors
The point: closing is a negotiation with three steps: stop accepting, let finish, then ask to stop. Each step has a limit.
Two-step shutdown
ExecutorService shows this in code, with two waits. If it is stuck even after that, end the process: a thread cannot be killed safely.Deploy
Thirty seconds to leave
A budget, if the platform gives 30 s
| Second | Step | If skipped |
|---|---|---|
| 0 | Fail the readiness check, wait until no new requests come | Requests are refused that others could take |
| 5 | shutdown: tasks are refused now | The queue never becomes empty |
| 5 to 20 | Accepted tasks finish | Work is lost |
| 20 | shutdownNow: interrupt, save the list | A hang until the platform kills us |
| 25 | Close connections, flush logs | Tasks fail because the database went first |
Stop
How a task can be stopped
| Language | Request | The task must |
|---|---|---|
| Java | Thread.interrupt | React to InterruptedException, or check isInterrupted in long loops |
| Python | No way to interrupt a thread | Check an Event between steps |
| C++20 | std::stop_token with std::jthread | Check stop_requested |
| JavaScript | AbortSignal | Pass it to fetch and check it |
Python
import threadingdef shrink_all(pictures, stop, save): for i, p in enumerate(pictures): if stop.is_set(): save(i) # the next start continues here return "stopped" # shrink p return "done"stop, place = threading.Event(), []stop.set()print(shrink_all(["a", "b"], stop, place.append), place)Errors
Where exceptions disappear
| Way in | The task throws | Who hears it |
|---|---|---|
Java submit, future ignored | Stored in the future | Nobody |
Java execute | Ends the worker, which is replaced | The uncaught exception handler |
| Java scheduled at a fixed rate | Later runs are suppressed | Only who looks at the future |
Python submit, future ignored | Stored in the future | Nobody |
C++ packaged_task, future dropped | Stored in the shared state | Nobody |
| JavaScript, promise not awaited | Unhandled rejection | The process may end |
End
Daemon threads
A daemon thread does not keep the program alive. That sounds convenient, but at the end it is cut off in the middle of a line, perhaps between two writes. Use normal threads and a clear shutdown. In Java a forgotten shutdown keeps the program alive, and that is a useful message: you have forgotten something.