Senior
Как настраивал ThreadPoolExecutor? Какие основные параметры?
sobes.tech AI
Answer from AI
ThreadPoolExecutor in Java is configured through several key parameters:
- corePoolSize — the number of threads that are always maintained in the pool, even if they are idle.
- maximumPoolSize — the maximum number of threads that can be created under high load.
- keepAliveTime — the time to wait before terminating excess threads (beyond corePoolSize) if they are idle.
- unit — the time unit for keepAliveTime.
- workQueue — the queue of tasks waiting to be executed.
- threadFactory — a factory for creating new threads (e.g., with custom naming).
- handler — the policy for handling tasks when the queue and pool are full (e.g., AbortPolicy, CallerRunsPolicy).
Example of creating a ThreadPoolExecutor:
ThreadPoolExecutor executor = new ThreadPoolExecutor(
5, // corePoolSize
10, // maximumPoolSize
60, TimeUnit.SECONDS, // keepAliveTime
new LinkedBlockingQueue<>(100), // workQueue
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.CallerRunsPolicy() // handler
);
Proper configuration depends on the nature of the tasks: if tasks are short and frequent — it's better to have more threads and a smaller queue; if tasks are long — the opposite. It is also important to consider hardware capabilities and response time requirements.