Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
When would you choose a fixed thread pool over a cached thread pool?
A fixed thread pool (Executors.newFixedThreadPool(n)) keeps exactly n threads alive for its lifetime and queues excess tasks on an unbounded queue. A cached thread pool (Executors.newCachedThreadPool()) creates new threads as needed, reuses idle ones, and lets threads that stay idle for 60 seconds terminate.
Choose a fixed pool when you want predictable, bounded resource usage, such as for CPU-bound work where you don't want more runnable threads than CPU cores, since extra threads there would only add context-switching overhead without more parallelism.
Choose a cached pool for many short-lived, bursty tasks, typically I/O-bound, where thread creation cost matters more than a hard concurrency cap, and load naturally ebbs and flows.
The risk with a cached pool is that it has no upper bound on thread count; under a sudden, sustained burst of tasks it can create an unbounded number of threads and exhaust system resources, whereas a fixed pool's bounded queue provides natural backpressure instead.
More Related questions...