Patterns and antipatterns question 154 of 180 mid
What is the thread-per-task versus task-per-thread distinction, and why did pools exist?
- They are the same thing
- Correct: Thread per work item does not scale on platform threads, so pools bound and reuse them
- Pools exist only to limit memory
- Tasks are always slower than threads
new Thread(task).start() per request works until it does not: each one reserves a stack, each start
is a syscall, and thousands of them thrash the scheduler. Pools decouple the unit of work (a task) from
the unit of execution (a thread), so you can have a million tasks and eight threads.
The cost of that decoupling is everything this repository has a topic about: queueing, rejection policies, thread locals that outlive tasks, cancellation that no longer maps to a thread, and stack traces that stop at the pool boundary.
Virtual threads restore the simple model. Executors.newVirtualThreadPerTaskExecutor() is thread per
task, and the reason it is now sensible is that the expensive resource the pool was amortising no
longer costs anything.
Quiz yourself on Patterns and antipatterns Suggest a correction