ExecutorService and Thread Pools
Thread pools reuse threads for many tasks. Interviewers ask about the types of executors, how ThreadPoolExecutor decides between queueing and creating threads, rejection policies, and how to size a pool.
What you will learn
- Explain the ThreadPoolExecutor parameters
- Know why Executors factory methods can be dangerous
- Size pools for CPU-bound vs I/O-bound work
- Shut down executors properly
Key concepts
ThreadPoolExecutor
corePoolSize, maximumPoolSize, keepAliveTime, workQueue, threadFactory and rejection handler. New tasks start a core thread first, then go to the queue, then create threads up to max, then are rejected.
Dangerous defaults
newFixedThreadPool and newSingleThreadExecutor use an unbounded queue, so tasks can pile up until OutOfMemoryError. newCachedThreadPool can create unbounded threads. Prefer an explicit ThreadPoolExecutor with a bounded queue.
Rejection policies
AbortPolicy (throw, default), CallerRunsPolicy (the caller runs it, which slows producers down naturally), DiscardPolicy, DiscardOldestPolicy.
Sizing
CPU-bound: about the number of cores. I/O-bound: cores × (1 + wait time / compute time), or simply use virtual threads.
Step by step
A production-ready pool
ThreadPoolExecutor pool = new ThreadPoolExecutor(
8, 16, // core, max
60, TimeUnit.SECONDS, // idle threads above core die after 60 s
new ArrayBlockingQueue<>(1_000), // bounded queue
Thread.ofPlatform().name("report-", 0).factory(),
new ThreadPoolExecutor.CallerRunsPolicy());Shut down cleanly
pool.shutdown(); // no new tasks, finish queued ones
if (!pool.awaitTermination(30, TimeUnit.SECONDS)) {
pool.shutdownNow(); // interrupt running tasks
}Examples
Spring @Async with a named executor
@Configuration
@EnableAsync
class AsyncConfig {
@Bean("emailExecutor")
ThreadPoolTaskExecutor emailExecutor() {
var ex = new ThreadPoolTaskExecutor();
ex.setCorePoolSize(4);
ex.setMaxPoolSize(8);
ex.setQueueCapacity(500);
ex.setThreadNamePrefix("email-");
return ex;
}
}
@Async("emailExecutor")
public CompletableFuture<Void> sendWelcome(User u) { ... }Practise it
Try these without looking back. If you can explain each one out loud, you are ready for this question.
- Explain why a pool with core 10, max 50 and an unbounded queue never grows past 10 threads.
- Use ScheduledExecutorService to refresh a cache every 5 minutes.
Interview questions
What interviewers ask next on this topic. Answer out loud first, then open the model answer.
submit vs execute?
execute(Runnable) returns nothing and an exception goes to the thread's uncaught exception handler. submit returns a Future and captures the exception inside it, which you only see when you call get(). Unchecked Futures can hide failures.
What is ForkJoinPool?
A pool with work stealing: each thread has its own deque and idle threads steal tasks from busy ones. It suits recursive divide-and-conquer tasks and backs parallel streams and CompletableFuture's default async methods.
Summary
Build pools explicitly with bounded queues and a rejection policy, size them by workload type, name threads, and shut them down with shutdown and awaitTermination.
Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus