Sobes.tech
Senior

Разница между newCachedThreadPool и newFixedThreadPool. Когда использовать каждый?

sobes.tech AI

Answer from AI

newFixedThreadPool creates a pool with a fixed number of threads. If all threads are busy, new tasks are queued and wait for their turn.

newCachedThreadPool creates a pool that dynamically creates new threads as needed and reuses inactive ones. Threads that are not used for 60 seconds are terminated.

When to use:

  • newFixedThreadPool — when you need to limit the number of concurrently working threads, for example, to control system load or resources.

  • newCachedThreadPool — when tasks are short and their number can vary greatly, requiring quick response and scaling based on load.

Example:

ExecutorService fixedPool = Executors.newFixedThreadPool(5); // maximum 5 threads
ExecutorService cachedPool = Executors.newCachedThreadPool(); // dynamic number of threads

Use fixedPool for stable load and predictable behavior, cachedPool for task spikes with quick execution.

Разница между newCachedThreadPool и… - sobes.tech