Junior — Middle
What is the difference between using FixedThreadPool and CachedThreadPool in thread management?
sobes.tech AI
Answer from AI
FixedThreadPool creates a pool with a fixed number of threads. All tasks are executed by these threads, and if a thread is busy, tasks are queued. This is useful when you need to limit the number of concurrently running threads and control the load.
CachedThreadPool creates new threads as needed and reuses inactive ones. If a thread is not used for some time, it is terminated. This pool is suitable for a large number of short tasks with unpredictable quantity.
Example of creating pools in Java:
ExecutorService fixedPool = Executors.newFixedThreadPool(5); // fixed pool of 5 threads
ExecutorService cachedPool = Executors.newCachedThreadPool(); // cached pool
The main difference is that the fixed pool limits the number of threads, while the cached pool creates and deletes them dynamically.