A tailor's shop has three tailors and a hook on the wall. Each order slip goes on the hook, and whichever tailor is free takes the next slip. The shop does not hire a new tailor for every customer. When the hook is full, the person at the counter asks the next customer to come back tomorrow. At closing time, the tailors finish the slips already on the hook, and nobody takes new ones.
Software has the same shape wherever many small jobs arrive and each one can be done in the background. A web server resizes uploaded photos, a shop sends order emails, and a crawler fetches pages. Starting a thread for each job is easy to write, and it works until the jobs arrive faster than they finish.
The Thread Pool pattern starts a fixed number of threads once and hands them tasks through a queue. In this article we build the photo service of a second-hand listings site twice. The first version starts a new thread for every upload. The second hands uploads to a small pool of workers. Then we look at what the pool costs, what to use in production, and how it differs from Object Pool and Producer-Consumer.
All the code is Java. Every snippet without a Sketch label is cut from a project that compiles: the first-version snippet from the thread-per-upload version, the rest from the finished design. Both programs run, and the outputs shown are what they print.
The photo service we are building
A seller lists a used scooter and uploads photos. For each photo, the site makes three thumbnails, 160, 480 and 1,080 pixels wide. Making them means decoding and resizing an image, which keeps a processor core busy for a while. The seller should not wait for it, so the upload is answered at once and the thumbnails are made in the background.
The service must:
- Answer an upload at once, and make the thumbnails on another thread.
- Use a fixed number of threads, however many uploads arrive.
- Hold a bounded number of waiting uploads, and answer "busy" when that limit is reached.
- Report each upload's state: in the queue, being made, ready, or failed with the reason.
- Keep working when one upload fails. A file that is not an image fails that upload only.
- Stop in two ways: finish everything accepted, or stop at once and say which uploads never started. After either, new uploads are refused as "closed", never as "busy".
- Run every accepted upload at most once, and lose none: it runs, or
shutdownNowhands it back. This holds however many requests arrive together.
This is the figure to draw first in an interview. It shows the two limits, the number of workers and the size of the queue, and the two refusals. Every later question, about failures, stopping or sizing, points at one part of it.
The first version: a new thread for every upload
The obvious service starts a thread for each upload:
public String upload(String listingId, int sizeKb) { Photo photo = new Photo("photo-" + lastId.incrementAndGet(), listingId, sizeKb); Thread worker = new Thread(() -> { try { ready.put(photo.id(), maker.make(photo)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }, "upload-" + photo.id()); worker.start(); threadsStarted.incrementAndGet(); return photo.id() + ": accepted"; }This code is correct for a few uploads a minute, and it answers the seller at once. The program runs it with three uploads one after another, then a burst of 300, then one file that is not an image:
1. Three uploads, one after another photo-1: accepted photo-1: ready photo-2: accepted photo-2: ready photo-3: accepted photo-3: ready threads started: 3 2. 300 uploads at once threads started: 303, making thumbnails at the same time: 300 3. A file that is not an image photo-304: accepted (error log) upload-photo-304: not an image photo-304: making thumbnails
Nothing caps the number of threads. 300 uploads at once start 300 threads, all making thumbnails at the same time. Each platform thread has its own stack and is scheduled by the operating system, so a few thousand uploads could slow the whole server or fail to start a thread at all. The machine has a few cores, and 300 threads only take turns on them.
A thread is started and thrown away for every upload. Starting a platform thread asks the operating system for one, which costs far more than a method call. This version pays it once for every upload.
A failure goes nowhere. photo-304 threw, the exception went to the error log, and the thread ended. Nothing recorded the failure, so the seller sees "making thumbnails" for ever.
Nothing can stop it cleanly. On shutdown, the service has no list of its threads, so it cannot wait for the uploads in progress or say which ones were lost.
The idea
The pattern works like this:
- A fixed number of threads start once and live as long as the pool. Each one loops: take a task, run it, take the next.
- Callers do not get a thread. They hand in a task, an object with one method to run, and the task waits in a queue until a thread is free.
- The queue has a fixed size. When it is full, the pool refuses the next task at once.
- Each task comes back to its caller as a handle, which later holds the task's result or what it threw.
- Stopping is part of the pool: it can finish what it accepted, or interrupt and hand back what never started.
The threads are the pool's workers. A task waiting to run is queued, and a task the pool turns away is rejected. Java's own name for the handle is a future.
Building it, step by step
Step 1: a task and its handle
The pool runs Callable tasks, Java's interface for "a piece of work that returns a value or throws". submit wraps each one in a TaskHandle, which a worker runs:
/** Called by a worker. Runs the task at most once and never throws. */ void run() { if (!state.compareAndSet(State.WAITING, State.RUNNING)) { return; // cancelled, or already run } try { result = task.call(); state.set(State.DONE); } catch (Throwable thrown) { // an Error too: the worker survives, and the caller is told failure = thrown; state.set(State.FAILED); } finally { finished.countDown(); } }Line 28 is a guard. compareAndSet moves the state from WAITING to RUNNING in one step, so a handle that was cancelled, or already run, would not run again. In this pool a handle reaches a worker once, and only while it is waiting, so the guard is a second line of defence. Line 32 runs the task. Whatever the task throws, lines 34 to 36 keep it in failure, and the finally on line 38 releases anyone waiting for the result.
The caller waits through get, for a bounded time:
/** The task's result, or TaskFailedException holding what it threw. */ public T get(Duration timeout) throws InterruptedException, TimeoutException { Objects.requireNonNull(timeout, "timeout"); if (!finished.await(TimeUnit.NANOSECONDS.convert(timeout), TimeUnit.NANOSECONDS)) { throw new TimeoutException("the task has not finished after " + timeout.toMillis() + " ms"); } return switch (state.get()) { case DONE -> result; case FAILED -> throw new TaskFailedException(failure); case CANCELLED -> throw new CancellationException("the task never started"); case WAITING, RUNNING -> throw new IllegalStateException("finished, but in state " + state.get()); }; }get returns the result, or throws TaskFailedException holding the very exception the task threw (line 63). A task that never started throws CancellationException (line 64). state(), resultNow() and failureNow() answer without waiting, which is what the photo service uses.
What happens when a task throws?
The worker dies and the pool starts a new one
The exception leaves the worker's loop, the thread ends, and the pool notices and starts a replacement. The pool's thread count stays right. But each failure costs a new thread, and the caller still has to be told some other way.
The handle keeps it and the worker carries onOur pick
run catches everything the task throws, including an Error, and keeps it in the handle. The worker takes the next task, and the caller sees the exact exception from get. The cost is that a failure nobody reads is lost quietly. If a caller never looks at the handle, a failed task leaves no sign anywhere. An OutOfMemoryError is kept the same way, so the worker carries on in a program that may no longer work.
Java's own pools do both, depending on the call. A task passed to submit gets a future that keeps whatever it throws, an Error too, and nothing reports it until someone calls get. A task passed to execute has no future: what it throws ends the worker and reaches the thread's uncaught-exception handler, and the pool starts a replacement.
The Producer-Consumer pattern page lets an Error end its worker, because settling payments in a program that may be broken is worse than stopping. A general pool runs any caller's code and cannot tell a fatal Error from a harmless one, so it hands the Error to the caller, who knows the task.
Step 2: workers that take from the queue
The constructor makes every worker with a ThreadFactory, as Java's executors do, and starts them once:
public ThreadPool(ThreadFactory threadFactory, int workerCount, int queueCapacity) { Objects.requireNonNull(threadFactory, "threadFactory"); if (workerCount < 1) { throw new IllegalArgumentException("workerCount must be at least 1, was " + workerCount); } if (queueCapacity < 1) { throw new IllegalArgumentException("queueCapacity must be at least 1, was " + queueCapacity); } this.queueCapacity = queueCapacity; this.liveWorkers = workerCount; List<Thread> threads = new ArrayList<>(); int started = 0; try { for (int i = 0; i < workerCount; i++) { Thread worker = Objects.requireNonNull(threadFactory.newThread(this::runWorker), "threadFactory returned null"); threads.add(worker); requireUnstartedPlatformThread(worker); worker.setDaemon(false); // a running pool keeps the program alive until it is shut down } this.workers = List.copyOf(threads); for (Thread worker : workers) { worker.start(); started++; } } catch (Throwable e) { // a bad thread, or the system refused one: stop any that are running stopAfterFailedStart(started); throw e; } }Line 55 refuses a thread the factory has already started, and a virtual thread, which is not meant to be pooled. Line 56 makes each worker a non-daemon thread, whatever the factory chose. The threads start on line 60, in the constructor's last step, after every field is set. Starting a thread makes everything written before it visible to that thread, so a worker never sees a half-built pool. The class is final, so no subclass constructor can run after the workers have started.
Starting a thread can fail: a system that has run out of threads throws an OutOfMemoryError from start. The workers already started would then wait for ever, and keep the program from exiting. Lines 63 to 65 stop any worker that is running, after a bad thread or a failed start, before the error goes on to the caller.
Each worker runs one loop for its whole life:
private void runWorker() { try { TaskHandle<?> task; while ((task = nextTask()) != null) { task.run(); // never throws: the handle keeps whatever the task threw completed.incrementAndGet(); } } finally { workerFinished(); } } /** The next task to run, or null when this worker should stop. */ private TaskHandle<?> nextTask() { lock.lock(); try { while (true) { if (runState == RunState.STOPPED) { return null; } TaskHandle<?> task = queue.pollFirst(); if (task != null) { Thread.interrupted(); // an interrupt left by the last task must not reach this one return task; } if (runState == RunState.SHUT_DOWN) { return null; } try { taskAdded.await(); } catch (InterruptedException e) { // shutdownNow, or a flag the last task left set: look at the state again } } } finally { lock.unlock(); } }nextTask holds the pool's lock while it looks at the queue. If a task is waiting, line 139 takes the oldest one. If not, line 148 waits on the taskAdded condition, which releases the lock until submit signals. A shut-down pool with an empty queue returns null on line 145, and the worker's loop ends.
Line 141 clears the interrupt flag before each task. A task may leave the flag set, and without this line the next task, for a different seller, would start already interrupted. Line 141 runs under the lock, and shutdownNow interrupts the workers under the same lock, so it never clears an interrupt meant to stop the pool. The finally on line 127 counts the worker out however its loop ends, which is what awaitTermination waits on.
Step 3: submitting, and a full queue
submit checks the pool's state and the queue's size, then adds the task and wakes one worker:
/** Queues the task, or refuses it at once if the pool is shut down or the queue is full. */ public <T> TaskHandle<T> submit(Callable<T> task) { Objects.requireNonNull(task, "task"); TaskHandle<T> handle = new TaskHandle<>(task); lock.lock(); try { if (runState != RunState.RUNNING) { throw new TaskRejectedException(TaskRejectedException.Reason.SHUT_DOWN, "the pool is shut down"); } if (queue.size() >= queueCapacity) { throw new TaskRejectedException(TaskRejectedException.Reason.QUEUE_FULL, "all " + queueCapacity + " places in the queue are taken"); } queue.addLast(handle); taskAdded.signal(); } finally { lock.unlock(); } return handle; }The order of the two checks matters. A full pool that is also shut down answers "shut down" (line 104), because the caller can never get in, while "full" means "try again later".
What happens when the queue is full?
Wait for a place
submit waits until a worker takes a task. Nothing is refused, but the request thread waits too, and the seller's upload page hangs while the server is busiest.
Run the task on the caller's thread
The request thread makes the thumbnails itself. This slows callers down exactly when the pool is behind, which pushes back on them. The cost is a request that takes seconds, and a request thread doing work meant for a worker.
Refuse at onceOur pick
submit throws TaskRejectedException with the reason QUEUE_FULL, and PhotoService tells the seller "busy, please try again". The server stays responsive, and the limit is visible. The cost is that some sellers must upload again.
PhotoService turns the two reasons into answers for the seller:
/** Answers the seller at once; the thumbnails are made later, on a worker. */ public String upload(String listingId, int sizeKb) { Photo photo = new Photo("photo-" + lastId.incrementAndGet(), listingId, sizeKb); try { jobs.put(photo.id(), pool.submit(() -> Objects.requireNonNull(maker.make(photo), "no thumbnails"))); return photo.id() + ": accepted"; } catch (TaskRejectedException e) { return switch (e.reason()) { case QUEUE_FULL -> photo.id() + ": busy, please try again"; case SHUT_DOWN -> photo.id() + ": uploads are closed"; }; } }How do callers and workers share the queue and the state?
A BlockingQueue and a volatile state field
Java's ArrayBlockingQueue already blocks and bounds. But submit would check the state, then offer the task: two steps. A shutdown between them can let the last worker see an empty queue and stop, and then the task joins a queue that no worker will ever read, unless submit checks the state again afterwards, as ThreadPoolExecutor does. Getting those re-checks right is the hard part of that design.
One lock over the queue and the stateOur pick
submit, nextTask, shutdown and shutdownNow all hold the same ReentrantLock. A task is either added before the state changes, and then a worker runs it or shutdownNow hands it back, or refused after. The cost is that every submit and every take goes through one lock, which is held only for a few lines.
Step 4: stopping
shutdown refuses new tasks and lets the queue drain. shutdownNow also interrupts the running tasks and returns the queued ones:
/** Refuses new tasks; the queued ones still run, then the workers stop. */ public void shutdown() { lock.lock(); try { if (runState == RunState.RUNNING) { runState = RunState.SHUT_DOWN; } taskAdded.signalAll(); } finally { lock.unlock(); } } /** * Refuses new tasks, interrupts the running ones, and returns the queued * tasks that never started. Their handles are cancelled. */ public List<Callable<?>> shutdownNow() { List<TaskHandle<?>> neverStarted; lock.lock(); try { runState = RunState.STOPPED; neverStarted = new ArrayList<>(queue); queue.clear(); taskAdded.signalAll(); for (Thread worker : workers) { worker.interrupt(); } } finally { lock.unlock(); } List<Callable<?>> tasks = new ArrayList<>(); for (TaskHandle<?> handle : neverStarted) { handle.cancel(); tasks.add(handle.task()); } return tasks; }Line 177 wakes every idle worker, so each one finds the queue empty and the pool shut down, and stops. In shutdownNow, line 193 empties the queue and line 196 interrupts every worker. A worker waiting for a task wakes and stops. A worker running a task sees an interrupt, and the task decides what to do with it. Ours stops part way, because the image library answers interrupts by throwing InterruptedException. A task that ignores interrupts runs to its end.
What happens to the queued tasks at shutdownNow?
Run them anyway
This is shutdown again, and "now" means nothing.
Drop them
The workers stop sooner, but a caller's get on those handles times out, and the task looks as if it is still queued. Nobody knows which uploads were lost.
Hand them back and cancel their handlesOur pick
shutdownNow returns the tasks that never started, so the caller can save them and run them again later. Line 203 cancels each handle, so its get ends at once with CancellationException. The cost is that the caller has to do something with the list.
awaitTermination waits until the last worker has stopped, or until a timeout, and answers which one happened.
demo/RaceCheck.java has 8 threads submit tasks to one pool at once, first with no shutdown and then with a shutdown while they are still submitting:
8 threads submitted 40,000 tasks to 4 workers all workers stopped: true ran exactly once: 40,000 of 40,000 ran twice: 0, never ran: 0 shut down while 8 threads were still submitting all workers stopped: true accepted but never ran: 0 ran twice: 0 refused but ran: 0
Every accepted task ran once, and no refused task ran. Without the lock, the queue is a plain ArrayDeque shared by many threads, which it does not allow. Two threads adding at once can overwrite each other's slot, so a task is accepted and never runs, and a resize can leave the deque corrupted. A task can also be accepted just after the last worker stopped.
The finished design
Here is one upload, traced through the objects:
The whole project is below. Click any class name in the code to open that class.
package pool; import java.time.Duration;import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.List;import java.util.Objects;import java.util.concurrent.Callable;import java.util.concurrent.ThreadFactory;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;import java.util.concurrent.atomic.AtomicLong;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock; /** * A fixed number of worker threads that take tasks from a bounded queue and * run them one at a time. Callers hand in tasks and get a TaskHandle back. */public final class ThreadPool { private enum RunState { RUNNING, SHUT_DOWN, STOPPED } private final int queueCapacity; private final List<Thread> workers; private final ReentrantLock lock = new ReentrantLock(); private final Condition taskAdded = lock.newCondition(); private final Condition allWorkersGone = lock.newCondition(); private final Deque<TaskHandle<?>> queue = new ArrayDeque<>(); // guarded by lock private RunState runState = RunState.RUNNING; // guarded by lock private int liveWorkers; // guarded by lock private final AtomicLong completed = new AtomicLong(); /** Workers named name-1, name-2 and so on. */ public ThreadPool(String name, int workerCount, int queueCapacity) { this(namedThreads(name), workerCount, queueCapacity); } public ThreadPool(ThreadFactory threadFactory, int workerCount, int queueCapacity) { Objects.requireNonNull(threadFactory, "threadFactory"); if (workerCount < 1) { throw new IllegalArgumentException("workerCount must be at least 1, was " + workerCount); } if (queueCapacity < 1) { throw new IllegalArgumentException("queueCapacity must be at least 1, was " + queueCapacity); } this.queueCapacity = queueCapacity; this.liveWorkers = workerCount; List<Thread> threads = new ArrayList<>(); int started = 0; try { for (int i = 0; i < workerCount; i++) { Thread worker = Objects.requireNonNull(threadFactory.newThread(this::runWorker), "threadFactory returned null"); threads.add(worker); requireUnstartedPlatformThread(worker); worker.setDaemon(false); // a running pool keeps the program alive until it is shut down } this.workers = List.copyOf(threads); for (Thread worker : workers) { worker.start(); started++; } } catch (Throwable e) { // a bad thread, or the system refused one: stop any that are running stopAfterFailedStart(started); throw e; } } private static void requireUnstartedPlatformThread(Thread worker) { if (worker.getState() != Thread.State.NEW) { throw new IllegalArgumentException("threadFactory returned a thread that was already started"); } if (worker.isVirtual()) { throw new IllegalArgumentException("workers must be platform threads; virtual threads are not pooled"); } } private void stopAfterFailedStart(int started) { lock.lock(); try { runState = RunState.STOPPED; liveWorkers = started; taskAdded.signalAll(); } finally { lock.unlock(); } } private static ThreadFactory namedThreads(String name) { Objects.requireNonNull(name, "name"); if (name.isBlank()) { throw new IllegalArgumentException("name must not be blank"); } AtomicInteger next = new AtomicInteger(); return task -> new Thread(task, name + "-" + next.incrementAndGet()); } /** Queues the task, or refuses it at once if the pool is shut down or the queue is full. */ public <T> TaskHandle<T> submit(Callable<T> task) { Objects.requireNonNull(task, "task"); TaskHandle<T> handle = new TaskHandle<>(task); lock.lock(); try { if (runState != RunState.RUNNING) { throw new TaskRejectedException(TaskRejectedException.Reason.SHUT_DOWN, "the pool is shut down"); } if (queue.size() >= queueCapacity) { throw new TaskRejectedException(TaskRejectedException.Reason.QUEUE_FULL, "all " + queueCapacity + " places in the queue are taken"); } queue.addLast(handle); taskAdded.signal(); } finally { lock.unlock(); } return handle; } private void runWorker() { try { TaskHandle<?> task; while ((task = nextTask()) != null) { task.run(); // never throws: the handle keeps whatever the task threw completed.incrementAndGet(); } } finally { workerFinished(); } } /** The next task to run, or null when this worker should stop. */ private TaskHandle<?> nextTask() { lock.lock(); try { while (true) { if (runState == RunState.STOPPED) { return null; } TaskHandle<?> task = queue.pollFirst(); if (task != null) { Thread.interrupted(); // an interrupt left by the last task must not reach this one return task; } if (runState == RunState.SHUT_DOWN) { return null; } try { taskAdded.await(); } catch (InterruptedException e) { // shutdownNow, or a flag the last task left set: look at the state again } } } finally { lock.unlock(); } } private void workerFinished() { lock.lock(); try { liveWorkers--; if (liveWorkers == 0) { allWorkersGone.signalAll(); } } finally { lock.unlock(); } } /** Refuses new tasks; the queued ones still run, then the workers stop. */ public void shutdown() { lock.lock(); try { if (runState == RunState.RUNNING) { runState = RunState.SHUT_DOWN; } taskAdded.signalAll(); } finally { lock.unlock(); } } /** * Refuses new tasks, interrupts the running ones, and returns the queued * tasks that never started. Their handles are cancelled. */ public List<Callable<?>> shutdownNow() { List<TaskHandle<?>> neverStarted; lock.lock(); try { runState = RunState.STOPPED; neverStarted = new ArrayList<>(queue); queue.clear(); taskAdded.signalAll(); for (Thread worker : workers) { worker.interrupt(); } } finally { lock.unlock(); } List<Callable<?>> tasks = new ArrayList<>(); for (TaskHandle<?> handle : neverStarted) { handle.cancel(); tasks.add(handle.task()); } return tasks; } /** Waits until every worker has stopped; false if the timeout passed first. */ public boolean awaitTermination(Duration timeout) throws InterruptedException { Objects.requireNonNull(timeout, "timeout"); long nanos = TimeUnit.NANOSECONDS.convert(timeout); lock.lock(); try { while (liveWorkers > 0) { if (nanos <= 0) { return false; } nanos = allWorkersGone.awaitNanos(nanos); } return true; } finally { lock.unlock(); } } public boolean isTerminated() { lock.lock(); try { return liveWorkers == 0; } finally { lock.unlock(); } } public int queuedCount() { lock.lock(); try { return queue.size(); } finally { lock.unlock(); } } public int liveWorkerCount() { lock.lock(); try { return liveWorkers; } finally { lock.unlock(); } } public long completedCount() { return completed.get(); } public int workerCount() { return workers.size(); }}demo/Main.java runs a pool of 2 workers with room for 3 tasks in the queue. Part 5 uses a second pool, so its photo numbers start again at 1:
1. Three uploads, one after another photo-1: accepted photo-1: ready, 160, 480, 1080 px photo-2: accepted photo-2: ready, 160, 480, 1080 px photo-3: accepted photo-3: ready, 160, 480, 1080 px photos made: 3, every one on thumbs-1 or thumbs-2: true 2. A file that is not an image photo-4: accepted photo-4: failed, not an image photo-5: accepted photo-5: ready, 160, 480, 1080 px workers still running: 2, every photo still on thumbs-1 or thumbs-2: true 3. Six uploads at once photo-6: accepted photo-7: accepted photo-8: accepted photo-9: accepted photo-10: accepted photo-11: busy, please try again [2 being made, 3 in the queue] photo-6: making thumbnails photo-8: in the queue photo-10: ready, 160, 480, 1080 px 4. shutdown: finish the queue, take nothing new photo-12: accepted photo-13: accepted photo-14: accepted photo-15: accepted photo-16: uploads are closed all workers stopped: true photo-14: ready, 160, 480, 1080 px photo-15: ready, 160, 480, 1080 px 5. A second pool, stopped with shutdownNow photo-1: accepted photo-2: accepted photo-3: accepted photo-4: accepted photo-5: accepted shutdownNow handed back 3 tasks that never started all workers stopped: true photo-1: stopped part way photo-2: stopped part way photo-3: never started photo-4: never started photo-5: never started
Part 1 is requirements 1 and 2: three photos, each made on one of the pool's 2 threads. In part 2, photo-4 failed with its reason, both workers are still running, and photo-5 was made on the same 2 threads (requirement 5). In part 3, two uploads are being made and three wait, so photo-11 is told "busy" (requirement 3), and the statuses show each state (requirement 4). Part 4 is shutdown: photo-14 and photo-15 were still in the queue, and both were made, while photo-16 was refused as "closed". Part 5 is shutdownNow: the two running uploads stopped part way, and the three queued ones never started (requirement 6).
What it costs
The number of threads has a ceiling we set. A burst of uploads becomes a longer queue and some "busy" answers, not more threads.
A task's failure is kept, but only someone who reads it will see it. The handle holds the exception. If no one reads the handle, the failure goes nowhere. The photo service reads a handle whenever a seller asks for that upload's status.
A task that waits for another task in the same pool can stop the pool. If both workers run tasks that wait on handles still in the queue, no worker is free to run those. They wait until their timeouts run out, or for ever with a get that has none.
Tasks finish in any order. They start in the order they arrived, but two workers run two at once, so photo-9 can be ready before photo-8. Work that must happen in order cannot rely on the pool for it.
A worker's thread-local values outlive the task. A ThreadLocal that one task sets is still there for the next task on the same worker, unless the task clears it.
The pool has to be stopped. The constructor makes every worker a non-daemon thread, so a pool nobody shuts down keeps the program running after main returns.
The service's map of handles only grows. Each handle keeps its task and its thumbnails. A real service would store each upload's status somewhere lasting and drop the handle once the task ends.
The size is a guess you have to tune. Making thumbnails keeps a core busy, so about one worker per core is enough, and more workers only take turns. Saving each thumbnail to storage instead means waiting on the network. While a worker waits it uses no core, so more workers keep the cores busy.
In production
In production Java, use java.util.concurrent instead of writing a pool. ThreadPoolExecutor does the same jobs, with more settings:
ExecutorService thumbnails = new ThreadPoolExecutor( 4, 4, // core and maximum threads 0, TimeUnit.SECONDS, // how long an extra thread may stay idle new ArrayBlockingQueue<>(100), // a bounded queue new ThreadPoolExecutor.AbortPolicy()); // refuse: throw RejectedExecutionExceptionAbortPolicy throws the same RejectedExecutionException when the queue is full and when the executor is shut down, so a caller tells "busy" from "closed" with isShutdown(). Unlike ours, a ThreadPoolExecutor starts its threads one at a time as tasks arrive, unless prestartAllCoreThreads() is called.
Stopping one usually combines both calls:
thumbnails.shutdown();if (!thumbnails.awaitTermination(30, TimeUnit.SECONDS)) { List<Runnable> neverStarted = thumbnails.shutdownNow(); // save these to run again later for (Runnable task : neverStarted) { if (task instanceof Future<?> future) { future.cancel(false); // or its get() waits for ever } }}Java's shutdownNow returns the queued tasks but does not cancel them. A task passed to submit is queued as its own future, so anyone waiting on its get waits for ever unless the code above cancels it. Our pool cancels them itself.
The other built-in policies are CallerRunsPolicy, which runs the task on the caller's thread, and two that discard a task. The shortcuts in Executors need care. Executors.newFixedThreadPool(n) uses an unbounded queue, so a burst is never refused and can use up memory instead. Executors.newCachedThreadPool() has no limit on threads. A ThreadPoolExecutor adds threads beyond its core size only when its queue refuses a task, so with an unbounded queue it never grows past the core size. The one exception is a core size of 0, where it starts a single thread so the queue is not left with none.
When a pool is too much
A pool earns its keep when tasks arrive often and must be bounded. Two cases need less.
If tasks are rare and one at a time is fast enough, a single background thread with a queue is simpler, and it keeps them in order. Executors.newSingleThreadExecutor() is that, ready-made.
If the work mostly waits, Java 21's virtual threads change the advice. They are cheap to create, so the usual advice is one virtual thread per task, and not to pool them. A Semaphore limits how many run at once, if the service behind them can only take so many:
Semaphore storageSlots = new Semaphore(50); // the storage service takes 50 at onceList<Future<String>> saves = new ArrayList<>();try (ExecutorService uploads = Executors.newVirtualThreadPerTaskExecutor()) { for (Thumbnail thumbnail : thumbnails) { saves.add(uploads.submit(() -> { storageSlots.acquire(); try { return storage.save(thumbnail); } finally { storageSlots.release(); } })); }} // close() waits for every taskfor (Future<String> save : saves) { save.get(); // throws if that save failed}Platform threads, and work that keeps a core busy, are still the ones to pool.
Thread Pool, Object Pool or Producer-Consumer?
All three keep a few things and share them out, so they are easy to confuse.
| Thread Pool | Object Pool | Producer-Consumer | |
|---|---|---|---|
| What is kept | A few threads | A few slow-to-make objects | A buffer between threads |
| What a caller gets | A handle for the result | The object itself, for a while | Nothing; it hands an item in |
| Who does the work | The pool's threads | The caller, using the object | The consumer threads |
| When it is full | The task is refused, or waits | The caller waits, then is refused | The producer waits, or is refused |
| Example | Making thumbnails | A database connection | Payment callbacks settled by workers |
The Object Pool pattern page lends each object to one caller, who uses it and gives it back. A thread pool never lends its threads: callers hand it tasks, and its own threads run them. The Producer-Consumer pattern page builds the queue between the two sides, and a thread pool is that queue with tasks as the items.
A short way to say it: an object pool lends its objects to you, and a thread pool takes your work from you.
In an interview
The pattern appears in questions about a job scheduler, a web crawler, a notification sender, and "implement your own thread pool". It also sits inside any design that does work in the background.
A good order for presenting it:
- Say what the tasks are and how many arrive. "Each upload makes three thumbnails, busy on the processor, and bursts of hundreds arrive."
- Draw the flow: submit, queue, workers, handle. Name the two limits and the two refusals.
- Then write the pool: the lock, the condition the workers wait on, the worker loop, and the two ways to stop.
Common mistakes:
- An unbounded queue. A burst fills memory instead of being refused, and the delay grows with no limit.
- Losing exceptions. A task's failure that nobody reads looks the same as success.
- Checking the state outside the lock. A task accepted just after the last worker stopped is never run, and its caller never gets a result.
- Forgetting to shut the pool down. The program cannot exit, and if it is killed, work in progress is cut off at random.
- Waiting on a task from inside the same pool. Every worker can end up waiting on work that no free worker can run.
- One pool size for all work. Work on the processor and work that waits need different sizes, and often different pools.
Summary
- Use a thread pool when many small tasks arrive and each can run in the background.
- Start a fixed number of workers once. Each takes the oldest task from a bounded queue, runs it, and takes the next.
- Give each caller a handle that holds the task's result or exactly what it threw, and keep the worker running after a failure.
- Refuse at once when the queue is full, and say "shut down" rather than "busy" once the pool is stopping.
- Check the state and change the queue under one lock, so no accepted task is lost at shutdown.
- In production, use a
ThreadPoolExecutorwith a bounded queue, and size it from the kind of work.