Building a Thread Pool From Scratch in Java: Worker Threads and a Task Queue
How a thread pool works inside, built step by step: worker threads looping over a bounded BlockingQueue, backpressure when the queue is full, surviving failing tasks, and a correct shutdown with poison pills and join. Plus the mistakes that simple pools usually make.
kvi5hnuCode Sprout team member8 min readOn this page
Part 3 looks underneath the tools from Parts 1 and 2. Virtual threads are scheduled by a ForkJoinPool and suspended with continuations. To understand those, it helps to start with the simplest scheduler of all: a thread pool. This article builds one from scratch. It's about 60 lines, and every line answers a question that real executors must also answer.
Why pools exist
Before virtual threads, threads were expensive (article 3), so applications didn't create one per task. They kept a fixed set of threads alive and fed them work. A pool gives you:
- A cap on threads, so a burst of work can't create thousands of OS threads and crash the process. The same cap limits load on downstream systems, as article 12 noted.
- Reuse: no thread-creation cost per task, so short tasks start immediately.
- Lifecycle management: one place to start, stop and monitor the threads.
- Separation of concerns: code submits tasks, and the pool decides which thread runs them.
With virtual threads, the first two reasons disappear for blocking work. But pools are still the right tool for CPU-bound work, for limiting parallelism, and for the scheduler that runs virtual threads themselves. Measurements bear this out: IBM's Open Liberty team found that their tuned thread pool outperformed virtual threads for some CPU-heavy workloads.
The design
A pool has two parts:
- A queue of tasks waiting to run. It must be safe for many threads to add to and take from, so a
BlockingQueueis the natural choice:take()waits while the queue is empty, andput()waits while it's full. - Worker threads, each running the same loop: take a task, run it, repeat.

The decisions that make it robust are in the details:
| Question | Answer in this pool |
|---|---|
| What if tasks arrive faster than they're processed? | a bounded queue: submit blocks when it's full (backpressure) instead of using unlimited memory |
| What if a task throws? | the worker catches it, counts it and continues. Otherwise one bad task would kill a worker, and the pool would slowly lose all its threads |
| How do workers know to stop? | poison pills: one special STOP task per worker, queued behind the real tasks |
How does close() know all work is done? | it joins every worker, which returns only after the worker has taken its pill, and therefore after every earlier task has finished |
| What if someone submits after close? | RejectedExecutionException, the same as the JDK's executors |
The code
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.atomic.AtomicInteger;
public class Solution {
/** A minimal fixed-size thread pool: N workers taking tasks from one bounded queue. */
static class MiniPool implements AutoCloseable {
private static final Runnable STOP = () -> {}; // "poison pill": tells one worker to exit
private final BlockingQueue<Runnable> queue;
private final List<Thread> workers = new ArrayList<>();
private final Object lock = new Object();
private boolean closed; // guarded by lock
final AtomicInteger failures = new AtomicInteger();
MiniPool(int threads, int queueCapacity) {
queue = new ArrayBlockingQueue<>(queueCapacity);
for (int i = 0; i < threads; i++) {
Thread worker = new Thread(this::workLoop, "mini-" + i);
workers.add(worker);
worker.start();
}
}
private void workLoop() {
while (true) {
Runnable task;
try {
task = queue.take(); // wait for work
} catch (InterruptedException e) {
return; // interrupted while idle: exit
}
if (task == STOP) return;
try {
task.run();
} catch (RuntimeException e) { // one bad task must not kill the worker
failures.incrementAndGet();
}
}
}
/** Blocks while the queue is full: that's backpressure on the caller. */
void submit(Runnable task) throws InterruptedException {
synchronized (lock) {
if (closed) throw new RejectedExecutionException("pool is closed");
queue.put(task);
}
}
/** Runs every task already submitted, then stops the workers and waits for them. */
@Override public void close() {
synchronized (lock) { closed = true; }
try {
for (int i = 0; i < workers.size(); i++) queue.put(STOP); // pills go behind real tasks
for (Thread w : workers) w.join();
} catch (InterruptedException e) {
workers.forEach(Thread::interrupt);
Thread.currentThread().interrupt();
}
}
}
static void work(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
public static void main(String[] args) throws InterruptedException {
AtomicInteger done = new AtomicInteger();
Set<String> threadsUsed = ConcurrentHashMap.newKeySet();
long start = System.nanoTime();
long submitMs;
MiniPool pool = new MiniPool(3, 3);
try (pool) {
for (int i = 0; i < 12; i++) {
int id = i;
pool.submit(() -> {
threadsUsed.add(Thread.currentThread().getName());
work(100);
if (id == 5) throw new IllegalStateException("task 5 failed");
done.incrementAndGet();
});
}
submitMs = (System.nanoTime() - start) / 1_000_000;
}
long totalMs = (System.nanoTime() - start) / 1_000_000;
System.out.println("submitting 12 tasks took about " + Math.round(submitMs / 100.0) * 100
+ " ms (submit blocked while 3 ran and 3 waited)");
System.out.println("all tasks finished after about " + Math.round(totalMs / 100.0) * 100 + " ms");
System.out.println("completed " + done.get() + ", failed " + pool.failures.get()
+ ", on threads " + new java.util.TreeSet<>(threadsUsed));
try {
pool.submit(() -> {});
} catch (RejectedExecutionException e) {
System.out.println("submit after close: " + e.getMessage());
}
}
}
Output (times may differ slightly):
submitting 12 tasks took about 200 ms (submit blocked while 3 ran and 3 waited)
all tasks finished after about 400 ms
completed 11, failed 1, on threads [mini-0, mini-1, mini-2]
submit after close: pool is closed
Walking through it:
- Backpressure. Three tasks run and three wait in the queue. The seventh
submitblocks until a worker frees a slot, so the loop needs about 200 ms just to hand over all 12 tasks. Without a bound, the queue would accept everything at once, and under a sustained overload it would grow until memory ran out. - Throughput. Twelve 100 ms tasks on three workers take four rounds, about 400 ms.
- Failure isolation. Task 5 threw, the worker counted it and carried on, and the other 11 tasks completed. All three workers survived.
- Clean shutdown.
close()returned only after every submitted task had run, and later submissions are rejected.
Mistakes simple pools make
Hand-written pools often look like this one but get one of these details wrong:
- "The queue is empty, so we're done." A
close()that waits untilqueue.isEmpty()and then interrupts the workers stops tasks that are still running: the queue empties when the last task is taken, not when it finishes. Joining the workers after poison pills (or using a counter of running tasks) fixes it. - Swallowing interrupts in the worker loop. A worker that catches
InterruptedExceptionaroundtake()and simply loops again can never be stopped by interruption. - Letting exceptions escape
run(). An uncaught exception ends the worker thread. After enough failures the pool has no threads, and tasks pile up forever with no error. - Unbounded queues. They hide overload until the heap fills up. A bound plus a policy (block, reject or run in the caller) makes overload visible.
ThreadGroupfor management. Thread groups are a legacy API, and since Java 19 several of their methods do nothing or have been removed. Keep your own list of worker threads instead.- A
volatile boolean runningflag alone. A worker blocked intake()never re-checks the flag. You still need pills or interrupts to wake it.
What the JDK adds
ThreadPoolExecutor (the next article) is this design with many more answers:
- Futures:
submitreturns aFuturefor the task's result or exception (article 21). - Shutdown variants:
shutdown()(finish queued work),shutdownNow()(interrupt running tasks and return the queued ones),awaitTermination(timeout)andclose(). - Elastic sizing: a core size and a maximum size, with idle threads above the core timing out.
- Rejection policies: abort, run in the caller's thread, discard, or discard the oldest.
- Hooks and metrics:
beforeExecute,afterExecute, active counts, completed counts and queue size.
In production, use the JDK's executors. Writing your own pool is for understanding them.
What's current
- Since Java 19,
ExecutorServiceextendsAutoCloseable.close()callsshutdown()and waits for all tasks, which is whatMiniPool.close()imitates. Executors.newVirtualThreadPerTaskExecutor()isn't a pool at all: it creates a new virtual thread for each task, and the reuse happens one level down, in the carriers.- The virtual-thread scheduler is itself a pool, a
ForkJoinPoolof carrier threads (article 23).
Common questions
Why use poison pills instead of interrupting the workers?
Interrupting stops a worker even if it's in the middle of a task, and it also interrupts the task's own blocking calls. Pills let queued work finish first. Real executors use both: shutdown() lets work finish, and shutdownNow() interrupts.
Why is submit synchronized?
Without the lock, a thread could check closed, then close() could enqueue the pills, and then the task could be added behind the pills, where no worker would ever run it. The lock makes "check, then enqueue" one step. A real executor solves this with an atomic state field instead of a lock.
What size should the queue be? Small enough that overload shows up quickly, large enough to absorb normal bursts. A queue holding a few seconds of work is a common starting point. An unlimited queue just delays the failure.
Should a pool ever use virtual threads as workers? No. The point of a pool is to reuse expensive threads, and virtual threads aren't expensive. For blocking tasks, use one virtual thread per task, and limit resources separately (article 12).
Summary
- A thread pool is a queue of tasks plus a fixed set of worker threads that loop: take, run, repeat.
- A bounded
BlockingQueuegives backpressure:submitblocks or rejects when the pool is overloaded. - Workers must catch task exceptions, or failures slowly kill the pool.
- Correct shutdown stops accepting tasks, lets queued tasks finish (poison pills), and joins the workers. An empty queue doesn't mean the work is done.
- The JDK's
ThreadPoolExecutoradds futures, elastic sizing, rejection policies, hooks and metrics.
Practice questions
A pool's close() method waits until queue.isEmpty() and then interrupts all workers. What can go wrong?
Answer
The queue becomes empty as soon as the last task is taken, while it may still be running. Interrupting the workers then interrupts those last tasks, so work is lost or left half done. Wait for the workers to finish instead, for example with poison pills and join(), or shutdown() plus awaitTermination() on a real executor.
In MiniPool, what would happen if workLoop didn't catch RuntimeException around task.run(), and three tasks failed?
Answer
Each failure would propagate out of run() and end that worker thread. After three failures, all three workers would be gone. Later tasks would sit in the queue forever, and submit would eventually block forever once the queue filled up, with no error explaining why.
Why are the poison pills put into the same queue as the tasks, rather than setting a flag?
Answer
The queue is FIFO, so pills placed after the real tasks are taken only once all earlier tasks have been taken. A worker blocked in take() also wakes up when a pill arrives, while it would never notice a flag change. One pill per worker ensures each worker exits exactly once.
Previous: Migrating to Java Virtual Threads: A Practical Checklist
Next: ThreadPoolExecutor in Java: Core and Maximum Size, Work Queues and Rejection Policies

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.