Junior — Middle
Can you explain the working principle of FixedThreadPool and how it differs from other thread pools?
sobes.tech AI
Answer from AI
FixedThreadPool is a type of thread pool in Java that creates a fixed number of threads and reuses them to execute tasks. When creating a FixedThreadPool, a fixed number of threads is specified, for example:
ExecutorService executor = Executors.newFixedThreadPool(5);
Working principle:
- If a new task arrives and there is a free thread, the task is executed immediately.
- If all threads are busy, the task is placed in a queue and waits for its turn.
- Threads are not created beyond the specified number, which helps control resource usage.
Differences from other pools:
- CachedThreadPool creates new threads as needed and removes unused ones; the number of threads is not fixed.
- SingleThreadExecutor contains only one thread; tasks are executed sequentially.
- ScheduledThreadPool is designed for delayed or periodic task execution.
FixedThreadPool is useful when you need to limit the number of tasks executed simultaneously and avoid creating too many threads.