Executors and Thread Pools
45 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)"Why use a thread pool, and how would you configure one?" is asked in nearly every Java backend interview. The interviewer is checking that you know the pool types, the order in which ThreadPoolExecutor uses core threads, queue and max, and how to shut a pool down.
Why thread pools: the cost of threads
ExecutorService is Java's thread pool interface. It reuses a fixed set of worker threads, queues extra tasks, returns a Future for each task and can be shut down cleanly.
A pool reuses a few threads for many tasks. This program submits six tasks to a pool of two threads and checks that no more than two threads did the work.
Example 1 · Six tasks on a fixed pool of two threads
import java.util.ArrayList;import java.util.List;import java.util.Set;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class FixedPoolDemo { public static void main(String[] args) throws Exception { ExecutorService pool = Executors.newFixedThreadPool(2); Set<String> threadsUsed = ConcurrentHashMap.newKeySet();
List<Future<String>> results = new ArrayList<>(); for (int roll = 101; roll <= 106; roll++) { int r = roll; results.add(pool.submit(() -> { threadsUsed.add(Thread.currentThread().getName()); return "hall ticket for " + r; })); }
for (Future<String> f : results) { System.out.println(f.get()); } pool.shutdown(); System.out.println("6 tasks, at most 2 threads used: " + (threadsUsed.size() <= 2)); }}hall ticket for 101 hall ticket for 102 hall ticket for 103 hall ticket for 104 hall ticket for 105 hall ticket for 106 6 tasks, at most 2 threads used: true
What this code does
- Six tasks are submitted, but only two worker threads run them; the others wait in the pool's queue. No thread is created per task.
- Results are read through the
Futures in submit order, so the output order is fixed even though the tasks may finish in any order.
Creating a platform thread is expensive: it needs an operating-system thread and stack memory (often around 1 MB), and switching between thousands of threads wastes CPU. A server that starts a thread per request can run out of memory under load. Model answer, spoken: "Pools reuse threads, cap how many run at once, and separate submitting a task from how it is run."
The family to name in an interview:
Executor: justexecute(Runnable).ExecutorService: addssubmit,invokeAll,invokeAny,shutdown,awaitTermination.ScheduledExecutorService: addsschedule,scheduleAtFixedRate,scheduleWithFixedDelay.Executors: factory methods that build common pools.
Executor types and ThreadPoolExecutor parameters
corePoolSize is the number of threads a pool keeps for normal load; maximumPoolSize is the most it may create when the queue is full. Extra threads above core die after keepAliveTime.
Two programs follow: the common ready-made pools, then a ThreadPoolExecutor with core 2, max 4 and a queue of 2 that accepts six tasks and rejects the seventh.
Example 2 · Single-thread, scheduled and cached executors
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;
public class ExecutorTypesDemo { public static void main(String[] args) throws Exception { ExecutorService single = Executors.newSingleThreadExecutor(); for (int i = 1; i <= 3; i++) { int step = i; single.execute(() -> System.out.println("single thread, step " + step)); // runs in order } single.shutdown(); single.awaitTermination(5, TimeUnit.SECONDS);
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); long start = System.nanoTime(); ScheduledFuture<String> reminder = scheduler.schedule(() -> "fee reminder sent", 200, TimeUnit.MILLISECONDS); System.out.println(reminder.get()); long waitedMs = (System.nanoTime() - start) / 1_000_000; System.out.println("waited at least 200 ms: " + (waitedMs >= 200)); scheduler.shutdown();
ExecutorService cached = Executors.newCachedThreadPool(); System.out.println("cached pool result: " + cached.submit(() -> 6 * 7).get()); cached.shutdown(); }}single thread, step 1 single thread, step 2 single thread, step 3 fee reminder sent waited at least 200 ms: true cached pool result: 42
What this code does
- A single-thread executor runs tasks one after another in submit order, so the three steps always print 1, 2, 3.
schedule(task, 200, MILLISECONDS)runs the task after the delay and returns aScheduledFuture; a cached pool creates a thread on demand for the short task.
Example 3 · core, queue, max and rejection in action
import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.CountDownLatch;import java.util.concurrent.RejectedExecutionException;import java.util.concurrent.ThreadPoolExecutor;import java.util.concurrent.TimeUnit;
public class PoolParametersDemo { public static void main(String[] args) throws InterruptedException { ThreadPoolExecutor pool = new ThreadPoolExecutor( 2, // corePoolSize 4, // maximumPoolSize 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2), // bounded work queue new ThreadPoolExecutor.AbortPolicy());
CountDownLatch gate = new CountDownLatch(1); Runnable slowTask = () -> { try { gate.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } };
for (int task = 1; task <= 7; task++) { try { pool.execute(slowTask); System.out.println("task " + task + " accepted: threads=" + pool.getPoolSize() + ", queued=" + pool.getQueue().size()); } catch (RejectedExecutionException e) { System.out.println("task " + task + " rejected: pool and queue are full"); } } gate.countDown(); pool.shutdown(); pool.awaitTermination(5, TimeUnit.SECONDS); System.out.println("completed tasks: " + pool.getCompletedTaskCount()); }}task 1 accepted: threads=1, queued=0 task 2 accepted: threads=2, queued=0 task 3 accepted: threads=2, queued=1 task 4 accepted: threads=2, queued=2 task 5 accepted: threads=3, queued=2 task 6 accepted: threads=4, queued=2 task 7 rejected: pool and queue are full completed tasks: 6
What this code does
- Tasks 1 and 2 get core threads, tasks 3 and 4 wait in the queue of size 2, tasks 5 and 6 force extra threads up to the max of 4, and task 7 is rejected with
RejectedExecutionException. - All tasks block on a latch so the pool stays full while we count; opening the gate lets the six accepted tasks complete.
Ready-made pools: newFixedThreadPool(n) has n threads and an unbounded queue; newCachedThreadPool() creates threads as needed and reuses idle ones for 60 s; newSingleThreadExecutor() runs tasks in order on one thread; newScheduledThreadPool(n) runs delayed and periodic tasks. All are built on ThreadPoolExecutor, whose seven settings are core size, max size, keep-alive time and unit, work queue, ThreadFactory and RejectedExecutionHandler.
A new task goes to a new core thread if fewer than core are running, else to the queue, else to a new extra thread up to max, else it is rejected:
- Order to remember: core threads, then queue, then extra threads up to max, then reject.
- With an unbounded queue,
maximumPoolSizenever matters, because the queue never fills. - Rejection policies:
AbortPolicy(default, throws),CallerRunsPolicy,DiscardPolicy,DiscardOldestPolicy. - CPU-bound pools: about the number of cores. I/O-bound pools: more threads, or virtual threads.
Predict the output
Predict the pool
Read the code, then pick what it prints.
Round 1 of 2
Core 2, max 4, a queue of 2, and 7 tasks that never finish.
submit vs execute; shutdown vs shutdownNow
execute(Runnable) returns nothing and prints a task's exception. submit(...) returns a Future that stores the exception, so it is lost unless someone calls get().
Two methods start a task, and two methods stop a pool. This program shows submit keeping an exception and shutdownNow interrupting a long task and returning the queued ones.
Example 4 · submit keeps exceptions; shutdownNow interrupts and returns queued tasks
import java.util.List;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;
public class SubmitShutdownDemo { public static void main(String[] args) throws Exception { ExecutorService pool = Executors.newSingleThreadExecutor();
Future<?> f = pool.submit(() -> { throw new IllegalArgumentException("bad roll number"); }); try { f.get(); } catch (ExecutionException e) { System.out.println("submit kept the exception: " + e.getCause().getMessage()); }
CountDownLatch started = new CountDownLatch(1); pool.execute(() -> { started.countDown(); try { Thread.sleep(10_000); System.out.println("long task finished"); } catch (InterruptedException e) { System.out.println("long task interrupted by shutdownNow"); } }); for (int i = 1; i <= 3; i++) { int n = i; pool.execute(() -> System.out.println("queued task " + n)); } started.await();
List<Runnable> neverRan = pool.shutdownNow(); pool.awaitTermination(5, TimeUnit.SECONDS); System.out.println("tasks returned by shutdownNow: " + neverRan.size()); System.out.println("isShutdown=" + pool.isShutdown() + ", isTerminated=" + pool.isTerminated()); }}submit kept the exception: bad roll number long task interrupted by shutdownNow tasks returned by shutdownNow: 3 isShutdown=true, isTerminated=true
What this code does
- The task submitted with
submitthrew, but nothing was printed untilf.get(), which rethrew it asExecutionException. Withexecuteit would go to the uncaught-exception handler instead. shutdownNow()interrupted the running long task and returned the three queued tasks that never ran;awaitTerminationthen waited until the pool was fully terminated.
With execute, an exception goes to the thread's uncaught-exception handler (usually printed) and the worker is replaced. With submit, get() throws ExecutionException. shutdown() stops accepting tasks but lets queued and running ones finish. shutdownNow() also interrupts running tasks and returns the tasks that never started.
Neither waits, so call awaitTermination(timeout). The usual pattern is shutdown, then awaitTermination, then shutdownNow if it times out.
Find the bug
Find the pool bug
Click the line that is wrong.
A payment task fails, but nothing is logged. Which line hides the failure?
Round 1 of 2CompletableFuture and ConcurrentHashMap in one minute
CompletableFuture is a Future you can chain without blocking. supplyAsync starts the work, thenApply transforms the result, and exceptionally or handle recover from errors.
A CompletableFuture chain replaces blocking get() calls. This program prices an item, adds GST and delivery, recovers from a failure, and counts visits on a ConcurrentHashMap.
Example 5 · CompletableFuture chain and ConcurrentHashMap.merge
import java.util.Map;import java.util.TreeMap;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ConcurrentHashMap;
public class CompletableFutureDemo { static int fetchPrice(String item) { return item.equals("headphones") ? 1500 : 400; }
public static void main(String[] args) { CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> fetchPrice("headphones")); CompletableFuture<Integer> withGst = price.thenApply(p -> p + p * 18 / 100); CompletableFuture<Integer> delivery = CompletableFuture.supplyAsync(() -> 60); CompletableFuture<Integer> total = withGst.thenCombine(delivery, Integer::sum); System.out.println("Total: " + total.join());
CompletableFuture<Integer> failing = CompletableFuture .supplyAsync(() -> Integer.parseInt("N/A")) .exceptionally(ex -> -1); System.out.println("With fallback: " + failing.join());
Map<String, Integer> visits = new ConcurrentHashMap<>(); CompletableFuture<?>[] jobs = new CompletableFuture<?>[4]; for (int i = 0; i < jobs.length; i++) { jobs[i] = CompletableFuture.runAsync(() -> { for (int k = 0; k < 1000; k++) { visits.merge("home", 1, Integer::sum); visits.merge("results", 1, Integer::sum); } }); } CompletableFuture.allOf(jobs).join(); System.out.println("Visits: " + new TreeMap<>(visits)); }}Total: 1830
With fallback: -1
Visits: {home=4000, results=4000}What this code does
- Price and delivery run asynchronously;
thenApplyadds GST (1500 + 270) andthenCombineadds delivery when both are ready: 1830.exceptionallyturns a failed parse into -1. - Four async jobs update the same
ConcurrentHashMapwithmerge, an atomic read-modify-write, so no visit is lost.allOf(...).join()waits for all of them.
supplyAsync runs on the common ForkJoinPool unless you pass an executor. thenCompose chains another async call, thenCombine joins two results, and allOf and anyOf wait for many. join() waits like get() but throws an unchecked CompletionException.
ConcurrentHashMap is the thread-safe map: reads do not lock, writes lock only part of the table, and putIfAbsent, computeIfAbsent and merge are atomic. It rejects null keys and values, and its iterators never throw ConcurrentModificationException.
Order of execution
Order the async chain
Put the CompletableFuture steps in the order they run.
Traps: forgetting shutdown and unbounded queues
Unbounded queue is a work queue with no size limit, such as the LinkedBlockingQueue behind newFixedThreadPool. If tasks arrive faster than they finish, it grows until the JVM runs out of memory.
Most pool bugs come from two traps: forgetting shutdown() and leaving the queue unbounded. Pool threads from Executors are non-daemon, so a forgotten pool keeps the JVM alive after main ends.
import java.util.concurrent.Executors;import java.util.concurrent.ThreadPoolExecutor;
public class UnboundedQueueSnip { public static void main(String[] args) { ThreadPoolExecutor pool = (ThreadPoolExecutor) Executors.newFixedThreadPool(2); int capacity = pool.getQueue().remainingCapacity(); System.out.println("queue capacity: " + capacity); System.out.println("same as Integer.MAX_VALUE: " + (capacity == Integer.MAX_VALUE)); pool.shutdown(); }}queue capacity: 2147483647 same as Integer.MAX_VALUE: true
Create pools once, reuse them, and shut them down when the application stops; a new pool per request leaks threads. newCachedThreadPool has the opposite risk: unbounded threads.
For production, build a ThreadPoolExecutor with a bounded queue and a rejection policy, or use a framework-managed pool such as Spring's ThreadPoolTaskExecutor.
Fix the error
Fix the compile error
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
The main method waits for the pool to finish.
Error
Demo.java:8: error: unreported exception InterruptedException; must be caught or declared to be thrown
pool.awaitTermination(5, TimeUnit.SECONDS);
^Next step
Check your understanding
12 quick questions