Junior — Middle
How can a thread pool be configured to avoid creating unnecessary threads?
sobes.tech AI
Answer from AI
To avoid creating unnecessary threads in the thread pool, you need to properly configure the pool parameters:
- Set a fixed or limited maximum number of threads. For example, use
Executors.newFixedThreadPool(n), wherenis the number of threads that can work simultaneously. - Use a task queue with a size limit to prevent new tasks from creating additional threads beyond the limit.
- Configure the task rejection policy (e.g., reject or wait) to avoid creating new threads when the queue is full.
- Use
ThreadPoolExecutorwith corePoolSize and maximumPoolSize set to the same value so that the pool does not expand beyond the specified size.
Example of creating a fixed thread pool in Android/Java:
ExecutorService executor = Executors.newFixedThreadPool(4); // maximum 4 threads