Choose a pool size and configure ThreadPoolExecutor
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)The right number of threads depends on what the tasks spend their time doing: calculating, or waiting. ThreadPoolExecutor, the class behind most Executors factory methods, lets you set that number yourself. It also lets you decide what happens when work piles up faster than the pool can finish it.
CPU-bound work: about one thread per core
CPU-bound work is work that spends almost all its time calculating, so its speed is set by the number of CPU cores, not by waiting.
A task is CPU-bound when it spends almost all its time calculating: hashing passwords, resizing photos, ranking 10 lakh exam scores. A CPU core can run only one thread at any instant, so such tasks go faster only while there are free cores.
int cores = Runtime.getRuntime().availableProcessors(); // e.g. 8ExecutorService cpuPool = Executors.newFixedThreadPool(cores);So for CPU-bound work, size the pool at about the number of cores, sometimes one more. Runtime.getRuntime().availableProcessors() tells you how many the JVM may use. More threads than cores do not add speed: they just take turns, and every switch between threads costs a little time.
Example 1 · CPU-bound work does not speed up past the core count
import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class CpuPoolSizeDemo { static int countPrimes(int from, int to) { // pure calculation, no waiting int count = 0; for (int n = Math.max(2, from); n < to; n++) { boolean prime = true; for (int d = 2; (long) d * d <= n; d++) { if (n % d == 0) { prime = false; break; } } if (prime) { count++; } } return count; }
static void timeWithPool(int threads, boolean print) throws Exception { List<Callable<Integer>> tasks = new ArrayList<>(); for (int i = 0; i < 48; i++) { int from = i * 50_000; tasks.add(() -> countPrimes(from, from + 50_000)); } ExecutorService pool = Executors.newFixedThreadPool(threads); long start = System.nanoTime(); int primes = 0; for (Future<Integer> f : pool.invokeAll(tasks)) { primes += f.get(); } long ms = (System.nanoTime() - start) / 1_000_000; pool.shutdown(); if (print) { System.out.printf("%3d threads: %4d ms (primes below 24 lakh: %d)%n", threads, ms, primes); } }
public static void main(String[] args) throws Exception { int cores = Runtime.getRuntime().availableProcessors(); System.out.println("Cores: " + cores); timeWithPool(cores, false); // warm-up run, not printed timeWithPool(1, true); timeWithPool(cores, true); timeWithPool(cores * 8, true); }}Cores: 12 1 threads: 724 ms (primes below 24 lakh: 176302) 12 threads: 311 ms (primes below 24 lakh: 176302) 96 threads: 388 ms (primes below 24 lakh: 176302)
What this code does
- This run was on a machine with 12 logical processors. Going from 1 thread to 12 made the work more than twice as fast; going from 12 to 96 made it no faster, here even a little slower, because there are no extra cores for the extra threads to use. Your core count and times will differ.
- The speed-up is less than 12 times because some tasks (the ones with bigger numbers) take longer than others, and other programs were using the CPU at the same time.
availableProcessors() counts logical processors, so a 4-core CPU with hyper-threading usually reports 8. In a container it reports the CPU limit given to the JVM.I/O-bound work: more threads, based on wait time
I/O-bound work is work that spends most of its time waiting for input or output, such as a database, a network call or a file, so extra threads can use the waiting time.
A task is I/O-bound when it spends most of its time waiting: on a database query, a payment API call or a file download. While a thread waits, its core is free, so more threads than cores now help.
Example 2 · Estimating pool sizes with the formula
public class PoolSizeFormulaDemo { static int poolSize(int cores, int waitMs, int computeMs) { return cores * (1 + waitMs / computeMs); }
static void show(String job, int cores, int waitMs, int computeMs) { System.out.printf("%-26s cores=%d wait=%3d ms compute=%3d ms -> %3d threads%n", job, cores, waitMs, computeMs, poolSize(cores, waitMs, computeMs)); }
public static void main(String[] args) { show("Password hashing (CPU)", 8, 0, 50); show("Result PDF generation", 8, 50, 50); show("UPI status API calls", 8, 90, 10); show("Hall ticket downloads", 4, 380, 20); }}Password hashing (CPU) cores=8 wait= 0 ms compute= 50 ms -> 8 threads Result PDF generation cores=8 wait= 50 ms compute= 50 ms -> 16 threads UPI status API calls cores=8 wait= 90 ms compute= 10 ms -> 80 threads Hall ticket downloads cores=4 wait=380 ms compute= 20 ms -> 80 threads
What this code does
- With no waiting, the formula gives exactly one thread per core. The more a task waits compared with how long it computes, the more threads can share each core.
- Integer division keeps the sketch simple; real numbers come from measuring your own tasks, and the result is a starting point to tune, not a law.
Example 3 · I/O-bound work does speed up with more threads
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
public class IoPoolSizeDemo { static void fetchMarks(int roll) { try { Thread.sleep(100); // waiting for the university server } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
static void timeWithPool(int threads) throws InterruptedException { ExecutorService pool = Executors.newFixedThreadPool(threads); long start = System.nanoTime(); for (int roll = 1; roll <= 40; roll++) { int r = roll; pool.submit(() -> fetchMarks(r)); } pool.shutdown(); pool.awaitTermination(10, TimeUnit.SECONDS); long ms = (System.nanoTime() - start) / 1_000_000; System.out.printf("%2d threads: 40 requests in %4d ms%n", threads, ms); }
public static void main(String[] args) throws InterruptedException { timeWithPool(4); timeWithPool(20); timeWithPool(40); }}4 threads: 40 requests in 1528 ms 20 threads: 40 requests in 344 ms 40 threads: 40 requests in 232 ms
What this code does
- Each request mostly waits (100 ms of
sleepstands in for the network). With 4 threads, the 40 requests need 10 rounds; with 40 threads, one round plus the cost of starting the threads. The core count barely matters here. - The times change a little on every run. In real systems the gain stops when the server you call becomes the bottleneck.
A common starting point, from the book Java Concurrency in Practice, is: threads ≈ cores × (1 + wait time ÷ compute time). With 8 cores and tasks that wait 90 ms and compute 10 ms, that is 8 × (1 + 9) = 80 threads.
Treat the result as a first guess, then measure and adjust. Also respect the limits of what you call: 80 threads sharing a database that allows 20 connections will mostly wait for connections.
Core size, max size, queue and rejection policy
ThreadPoolExecutor is the class behind most thread pools. You set its core size, maximum size, work queue and rejection policy yourself.
A ThreadPoolExecutor is built from a core pool size, a maximum pool size, a keep-alive time for idle extra threads, a work queue, an optional thread factory and a rejection policy. When a task arrives, the pool decides what to do in four steps.
- Fewer threads than the core size? Start a new thread for the task.
- Otherwise, room in the queue? Put the task in the queue.
- Queue full, but fewer threads than the maximum? Start an extra thread.
- Queue full and at the maximum? Hand the task to the rejection policy.
Example 4 · Watching a ThreadPoolExecutor grow, queue and reject
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.RejectedExecutionException;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;
public class PoolRulesDemo { public static void main(String[] args) throws InterruptedException { ThreadPoolExecutor pool = new ThreadPoolExecutor( 2, // core pool size 4, // maximum pool size 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2), // bounded queue: 2 waiting tasks new ThreadPoolExecutor.AbortPolicy());
for (int n = 1; n <= 8; n++) { try { pool.execute(() -> { try { Thread.sleep(200); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); System.out.println("task " + n + " -> threads " + pool.getPoolSize() + ", queued " + pool.getQueue().size()); } catch (RejectedExecutionException e) { System.out.println("task " + n + " -> REJECTED"); } } pool.shutdown(); pool.awaitTermination(5, TimeUnit.SECONDS); System.out.println("Completed: " + pool.getCompletedTaskCount()); }}task 1 -> threads 1, queued 0 task 2 -> threads 2, queued 0 task 3 -> threads 2, queued 1 task 4 -> threads 2, queued 2 task 5 -> threads 3, queued 2 task 6 -> threads 4, queued 2 task 7 -> REJECTED task 8 -> REJECTED Completed: 6
What this code does
- Tasks 1 and 2 start core threads. Extra threads that stay idle end after 30 seconds. Tasks 3 and 4 wait in the queue, even though the maximum is 4: extra threads start only when the queue is full. Tasks 5 and 6 then get extra threads 3 and 4.
- With 4 threads busy and 2 tasks queued, there is no room left, so
AbortPolicyrejects tasks 7 and 8 withRejectedExecutionException. Exactly 6 tasks complete.
Example 5 · CallerRunsPolicy makes the sender do the work
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;
public class CallerRunsDemo { static final List<String> log = new ArrayList<>();
static void pack(int order, int ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } synchronized (log) { log.add("order " + order + " packed by " + Thread.currentThread().getName()); } }
public static void main(String[] args) throws InterruptedException { AtomicInteger packerNo = new AtomicInteger(); ThreadPoolExecutor packers = new ThreadPoolExecutor( 1, 1, 0, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1), r -> new Thread(r, "packer-" + packerNo.incrementAndGet()), new ThreadPoolExecutor.CallerRunsPolicy());
packers.execute(() -> pack(1, 200)); // the packer is busy for 200 ms packers.execute(() -> pack(2, 50)); // waits in the one-slot queue packers.execute(() -> pack(3, 50)); // no room: main packs it itself packers.execute(() -> pack(4, 50));
packers.shutdown(); packers.awaitTermination(5, TimeUnit.SECONDS); log.sort(null); log.forEach(System.out::println); }}order 1 packed by packer-1 order 2 packed by packer-1 order 3 packed by main order 4 packed by main
What this code does
- The pool has one packer and one queue slot. Orders 3 and 4 find both taken, so
CallerRunsPolicyruns them on the thread that calledexecute:main. Nothing is lost and no exception is thrown. - While
mainis busy packing, it cannot submit more orders. That is back-pressure: when the pool is full, the producer slows down by itself. TheThreadFactorylambda gives the threads readable names likepacker-1.
AbortPolicy(the default): throwRejectedExecutionException.CallerRunsPolicy: the thread that calledsubmitruns the task itself, which slows down the producer.DiscardPolicydrops the new task silently;DiscardOldestPolicydrops the oldest queued task and retries.- Surprise: extra threads above the core size start only when the queue is full. With an unbounded queue, the maximum is never used.
The danger of unbounded queues and cached pools
newFixedThreadPool(n) uses a LinkedBlockingQueue with no size limit. If tasks arrive faster than they finish, the queue just grows, and every waiting task holds memory.
Example 6 · An unbounded queue and an unbounded cached pool
import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;
public class UnboundedDangerDemo { static void slowRequest() { try { Thread.sleep(300); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
public static void main(String[] args) throws InterruptedException { ThreadPoolExecutor fixed = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); for (int i = 0; i < 10_000; i++) { fixed.execute(UnboundedDangerDemo::slowRequest); } System.out.println("Fixed pool: threads " + fixed.getPoolSize() + ", waiting in queue " + fixed.getQueue().size()); List<Runnable> dropped = fixed.shutdownNow(); System.out.println("Dropped by shutdownNow: " + dropped.size());
ThreadPoolExecutor cached = (ThreadPoolExecutor) Executors.newCachedThreadPool(); for (int i = 0; i < 300; i++) { cached.execute(UnboundedDangerDemo::slowRequest); } System.out.println("Cached pool: threads " + cached.getPoolSize()); cached.shutdown(); cached.awaitTermination(5, TimeUnit.SECONDS); fixed.awaitTermination(5, TimeUnit.SECONDS); }}Fixed pool: threads 2, waiting in queue 9998 Dropped by shutdownNow: 9998 Cached pool: threads 300
What this code does
- The fixed pool accepted all 10,000 slow requests without complaint: 2 run and 9,998 sit in its unbounded queue, each one holding memory. With a real stream of requests the queue keeps growing until something breaks.
- The cached pool created a new thread for every one of the 300 slow requests. Both factory pools can be cast to
ThreadPoolExecutorto read these numbers, which is handy when monitoring a pool.
Waiting times get longer and longer, and in the end the JVM can run out of memory. Nothing tells the senders to slow down.
newCachedThreadPool() has the opposite problem: no queue at all and no limit on threads. A burst of slow tasks creates one thread per task, thousands of them. For servers that take work from outside, such as a Tatkal booking API, build the pool yourself: a fixed number of threads, a bounded queue such as ArrayBlockingQueue, and a rejection policy you chose on purpose.
Next step
Check your understanding
12 quick questions