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

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

The documentation of 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

SecondStepIf skipped
0Fail the readiness check, wait until no new requests comeRequests are refused that others could take
5shutdown: tasks are refused nowThe queue never becomes empty
5 to 20Accepted tasks finishWork is lost
20shutdownNow: interrupt, save the listA hang until the platform kills us
25Close connections, flush logsTasks fail because the database went first
Close in the reverse order of creation: the pool uses the database, so the pool ends first.

Stop

How a task can be stopped

LanguageRequestThe task must
JavaThread.interruptReact to InterruptedException, or check isInterrupted in long loops
PythonNo way to interrupt a threadCheck an Event between steps
C++20std::stop_token with std::jthreadCheck stop_requested
JavaScriptAbortSignalPass it to fetch and check it
All four are requests. A task that computes for an hour without checking takes an hour. Cut it into steps.
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)
A long task in steps. It saves its place and leaves politely.
Edit and run it in your browser

Errors

Where exceptions disappear

Way inThe task throwsWho hears it
Java submit, future ignoredStored in the futureNobody
Java executeEnds the worker, which is replacedThe uncaught exception handler
Java scheduled at a fixed rateLater runs are suppressedOnly who looks at the future
Python submit, future ignoredStored in the futureNobody
C++ packaged_task, future droppedStored in the shared stateNobody
JavaScript, promise not awaitedUnhandled rejectionThe process may end
The first row is the most common silent failure of all. The third surprises people at night: one exception, and the job never runs again. Catch inside the task.

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.