Lesson · Executors, Thread Pools & Async Programming
Why Executors: separate the task from the execution policy
13 min readWhy Executors?
The one-thread-per-task loop answers a single question and defers five others: how many threads, what waits, what happens when nothing can wait, who stops them, and how results come back. An executor splits the code into two halves, the task describes what to do and the executor owns how, where and when it runs. Every pool in java.util.concurrent is an answer to that split.
The loop that ships first
The first version of a concurrent batch job is a loop: one task, one thread, start. It is honest code, and it works until load arrives, because every iteration makes a decision nobody can take back. It asks the operating system for a real thread, right now, with no ceiling anywhere in sight.
Six tasks means six threads. Six hundred tasks means six hundred threads, each with a stack reservation of roughly a megabyte with HotSpot defaults, plus a creation syscall and scheduler bookkeeping. Nothing in the loop asks whether the machine can hold six hundred threads, and nothing gives the surplus somewhere to wait: unbounded creation is the policy, and it was chosen by accident.
Then the second problem arrives. Threads created this way are unreusable and unowned: when a task finishes its thread is gone, the next submission pays the creation cost again, and no object holds a reference that could name, count or stop the threads.
for (Order order : batch) { new Thread(() -> ship(order), "ship-" + order.id()).start(); // one task, one thread, no cap }
Thread-per-task without a policy is an outage waiting for load. The loop is not wrong, it is missing its policy half.
Five decisions the loop leaves open
A thread per task answers one question, how do I run this now, and defers five others. Each one is a decision the system still has to make; with a bare thread it gets made by accident, per call site, at the worst possible moment.
- How many threads may exist at once. Nothing caps concurrency, so the cap is whatever load happens to be, and the machine discovers it the hard way.
- What happens when demand exceeds capacity. There is no queue, so there is no waiting room and no backpressure: every arrival becomes a thread immediately.
- What a thread is called, and whether it is a daemon. Naming, priority and daemon status are set per thread at creation, scattered across every site that starts one.
- Who stops the work. No object owns the threads, so shutdown is your own bookkeeping: shared flags, interrupts, joins. Get one detail wrong and the JVM never exits or a task hangs forever.
- How results and failures come back. A Runnable returns nothing, and its exception goes to the thread's handler chain (the Uncaught Exception Handler lesson owns that routing). Getting a value back means inventing fields and latches, or moving to a Future.
A bare thread answers how to run one task and defers every question about many.
The task and the policy, separated
The split is the whole idea: a task describes what to do, and an executor decides how, where and when it runs. In Java the task is a Runnable (no result) or a Callable (a value and a checked failure), and the executor is any implementation of java.util.concurrent.Executor, whose entire surface is one method, execute(Runnable command). Decoupling task submission from the mechanics of how each task will run is the documented contract of that interface, not an accident of its design.
Count the mapping: many tasks, a smaller number of threads, and the executor picks that number. The tasks never see those threads, and each thread sees the next item from a queue rather than a specific task. That M to N relationship is the scheduling layer the loop was missing.
Because the two halves are separate, the same task code runs unchanged under wildly different policies: two workers, a work-stealing pool, or a fresh virtual thread per task. Testing a task stops requiring a controlled thread environment, and changing capacity stops requiring a change to every call site.
The task describes work; the executor owns the how.
Two pipelines, one burst
same six tasks, two execution policies
manual: one thread per task
spiky- no queue: arrivals wait nowhere
- no cap: thread count follows load
- no reuse: creation paid per task
- no owner: nothing to stop or name
Six tasks create six OS threads, each with its own stack reservation. One hundred submissions ask for one hundred threads, and the machine decides what happens next.
executor: tasks to queue to workers
boundedThe same six tasks run two at a time, the surplus waits in a queue whose capacity is the memory bound, and the policy lives in one named object with a shutdown path.
One burst of load, answered two ways: the left pipeline turns load into threads, the right one turns load into waiting, with a cap, a queue and an owner.
The queue is the buffer, and the buffer is the backpressure
Every executor has somewhere for waiting tasks to sit between submission and execution. That somewhere is a queue, and it does three jobs at once: it absorbs a burst, it holds the excess the workers cannot run yet, and its capacity decides when submission has to slow down.
This is the bounded buffer from the producer-consumer lesson wearing different clothes. The submitter is the producer, the worker threads are the consumers, and the queue is the buffer whose capacity is the memory bound. Nothing about the pattern changes; an executor is where you stop hand-rolling it.
Capacity and its full case are two separate questions, and java.util.concurrent answers them with two separate components: the queue decides how much can wait, and a rejection handler decides what happens when the queue refuses another item. Block the submitter, throw, or drop the task: each is a policy, and each belongs to the executor rather than to the task.
A queue turns a spike into a wait; its bound turns the wait into backpressure. Without a bound, the wait turns into memory pressure instead.
The policy questions, named
Once the policy is an object, every decision the loop left open becomes a parameter you can read, review and change. The table below is the checklist worth running against any thread creation you find: each row is a question the executor answers once, and the last column names the lesson that goes deeper.
The lab underneath submits six identical tasks under three policies. Watch the counters and the thread cost chip: same tasks, three different answers to the same five questions.
| Decision | Bare thread | Executor |
|---|---|---|
| How many run at once | as many as load creates | pool size, core and max (thread pools lesson) |
| What waits when capacity is full | nothing: a new thread instead | queue capacity, then a rejection policy |
| How threads are created | new Thread per task | a ThreadFactory: naming, daemon flag, priority |
| How the work stops | your own flags and joins | shutdown, shutdownNow, awaitTermination (next lesson) |
| How results return | shared fields and latches | submit returns a Future; invokeAll, invokeAny, CompletionService |
| Where failures go | the thread's handler chain | execute routes to the chain, submit stores in the Future (Uncaught Exception Handler lesson) |
| What can be tested | everything at once | the task alone, then the policy separately |
A policy named in one object can be reviewed and changed; a policy spread over call sites can only be discovered.
Six tasks, three policies
tasks t1 to t6
one platform thread per task, created at submission time
Six tasks, six start() calls. Every task gets a platform thread immediately, because there is nowhere for a task to wait: no queue exists between the loop and the operating system.
What the split unlocks
The seam between task and policy is also what makes the rest of java.util.concurrent possible. Once a task is a value handed to an executor, libraries can wrap it, batch it, race it and compose it without knowing anything about the work inside.
- One task, later result.
submit(Callable)returns a Future: a placeholder you can read, cancel or combine. Owned by the next lesson. - A batch of tasks. invokeAll and invokeAny take a list and give you either all the results in submission order or the first success. Owned by the next lesson.
- Results as they finish. A CompletionService reorders results into completion order, which is what you want when task durations differ. Owned by the next lesson.
- Composition without blocking. CompletableFuture chains stages; it is built entirely on the idea that a task is something you can hand over. It has its own lesson later in this part.
Once tasks are values handed to an executor, composition becomes library work.
Thread-per-task, cheap again
Java 21 changes the cost side of the ledger. A virtual thread is a thread the JVM schedules itself: the stack starts small and grows on demand, and a small pool of carrier platform threads runs the virtual threads that are ready to make progress. Thread-per-task, the very shape this lesson opened by criticising, becomes cheap again: Executors.newVirtualThreadPerTaskExecutor() accepts every task and starts a virtual thread for each, and its javadoc states plainly that the number of threads it creates is unbounded.
What did not change is the policy half. Millions of simultaneous tasks still compete for sockets, file handles, database connections and downstream services, so the bound has to live somewhere: a Semaphore around the scarce resource, a bounded queue, or a pool whose size you chose on purpose. The executor seam is exactly where that bound belongs, which is why virtual threads arrive as executor implementations rather than as a replacement for the interface.
- The cost argument falls. Thread creation stops being the reason to pool when a thread is kilobytes instead of a megabyte reservation (see the Virtual Threads part).
- The policy argument stands. Naming, error propagation, cancellation, bounded concurrency and shutdown are still decisions somebody has to make.
- The mental model survives. Task on one side, executor with a policy on the other; only the default size of the right-hand side changed.
Virtual threads remove the cost of having many threads; they do not remove the question of how many tasks should be in flight.
Remember
When a bare thread is in front of you, ask the five questions: cap, queue, factory, lifecycle, results. When an executor is in front of you, the same five answers are named, and you can change them without editing a single task.
Keep the sentence that started everything close, because every class in java.util.concurrent that runs tasks is some answer to it.
If the policy is not written down in one place, it is re-implemented, a little differently, at every call site.
Two hundred submissions, two hundred threads
A handler starts a thread per incoming job. At ten requests per second that is fine; at ten thousand it is a resource incident, because thread count becomes load, creation cost is paid per task, and the cap the machine needed never existed. The repair is not a shorter sleep or a bigger box: hand the tasks to an executor and move the decisions into one object that has a bound, a queue, names and a shutdown path.
Interview angles
Why is one thread per task a problem?+
Because the loop creates threads with no bound and no queue: every arrival becomes a new OS thread with its own stack, so load turns into thread count and the machine pays in memory, creation syscalls and context switches. Nothing reuses the threads afterwards, and nothing owns them well enough to stop them.
What is an executor actually responsible for?+
The execution policy: how many threads run, where surplus work waits, who creates and names those threads, what happens when capacity is exhausted, and how everything stops. The task stays a Runnable or Callable and describes only the work.
That is the M to N relationship in one sentence: many tasks share fewer threads, and the executor owns the mapping, including the queue between submission and execution.
Where does backpressure come from in an executor?+
From the queue between submission and execution plus the policy for when it is full: block the submitter, reject the task, or drop it. Without a bound there is no backpressure at all, only growing memory.
Does submitting tasks to a pool make each task faster?+
No. A pool amortises thread creation and bounds how much work runs at once, which improves throughput and protects the machine under load. A task that waited in a queue starts later than it would have on a fresh thread, so per-task latency can get worse.
Common misconception: A pool is assumed to be a speed-up. It is a capacity policy, not a turbo button.
Java 21 makes thread-per-task cheap again. Do executors still matter?+
Yes, because cost was only half the argument. Virtual threads make the thread part cheap, but bounded concurrency, naming, cancellation, error propagation and shutdown are still decisions, and the executor seam is where they belong.
newVirtualThreadPerTaskExecutor() is itself an executor: thread-per-task expressed as a policy, through the same interface every other pool implements.
How would you retrofit an executor onto a loop of new Thread(task).start() calls?+
Keep the task code, replace the loop with one executor created and owned in a single place, submit the tasks to it instead of starting threads, and give that executor a shutdown path. The five questions from this lesson become the pool's constructor arguments.
Follow-up: Which of those decisions can be changed without touching a single task, and which one would force edits at every call site?