Java Concurrency Interview

Patterns and antipatterns question 154 of 180 mid

What is the thread-per-task versus task-per-thread distinction, and why did pools exist?

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.

design executors

Quiz yourself on Patterns and antipatterns Suggest a correction