ThreadPoolExecutor Implementation
2 mins
ThreadPoolExecutor is the primary implementation of ExecutorService. It is a sophisticated piece of engineering that manages a pool of worker threads, a task queue, and various lifecycle states.
Source Code #
Canonical Usage #
When to use: Use ThreadPoolExecutor when you need a pool of reusable threads to handle a high volume of short-lived tasks, or when you need fine-grained control over how those threads are managed, how many tasks can be queued, and what happens when the system is overloaded.
Common Patterns:
- Fixed Pool Size: For applications with a predictable, steady workload.
- Cached Pool Size: For applications with many short-lived, bursty tasks.
- Single Thread Pool: When you need to ensure tasks are executed sequentially and in order.
- Custom Rejection Policies: Deciding what to do when the pool is full and the queue is full.
// Fixed thread pool for CPU-bound tasks
ExecutorService cpuPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
// Custom ThreadPoolExecutor for bounded work with a custom rejection policy
BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(100);
ExecutorService customPool = new ThreadPoolExecutor(
10, 50, 60L, TimeUnit.SECONDS,
queue,
new ThreadPoolExecutor.CallerRunsPolicy() // Run in caller thread if pool is full
);
Core Configuration Parameters #
- corePoolSize: The number of threads to keep in the pool, even if they are idle.
- maximumPoolSize: The maximum number of threads allowed in the pool.
- keepAliveTime: When the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.
- workQueue: The queue used for holding tasks before they are executed.