Java Core & JVM (50 Qs)•Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)
How do you correctly configure and size ThreadPoolExecutor in production?
senior LevelCode ExampleSystem Design
In Simple Words:
Never use Executors.newCachedThreadPool() (unbounded thread creation causes OOM) or Executors.newFixedThreadPool() (unbounded LinkedBlockingQueue exhausts memory under load). Always construct ThreadPoolExecutor explicitly with bounded queues and saturation rejection policies.
Key Parameters:
corePoolSize: Minimum number of threads kept alive in the pool.maximumPoolSize: Ceiling of threads allowed when work queue fills.workQueue: Bounded queue (e.g.,ArrayBlockingQueue(1000)).RejectedExecutionHandler: Action when queue and max threads are saturated (CallerRunsPolicy,AbortPolicy,DiscardOldestPolicy).
java
int cores = Runtime.getRuntime().availableProcessors();
ThreadPoolExecutor executor = new ThreadPoolExecutor(
cores * 2, // core pool size
cores * 4, // maximum pool size
60L, TimeUnit.SECONDS, // keep alive for idle threads
new ArrayBlockingQueue<>(5000), // bounded task queue
new ThreadFactoryBuilder().setNameFormat("order-worker-%d").build(),
new ThreadPoolExecutor.CallerRunsPolicy() // Backpressure: executes task on caller thread!
);
Sizing Rule of Thumb:
- CPU-Bound Tasks: $N_{\text{threads}} = N_{\text{cores}} + 1$ (avoids CPU context switching).
- IO-Bound Tasks (Database, HTTP calls): $N_{\text{threads}} = N_{\text{cores}} \times (1 + \frac{\text{Wait Time}}{\text{Service Time}})$.