Junior — Middle
What implementations of the ExecutorService interface do you know, and how do they differ?
sobes.tech AI
Answer from AI
ExecutorService is an interface for managing a thread pool and executing tasks asynchronously. The main implementations from the Java standard library:
- ThreadPoolExecutor — the most flexible and commonly used implementation, allows configuring the pool size, task queue, and overload handling policy.
- ScheduledThreadPoolExecutor — an extension of ThreadPoolExecutor, supports scheduling tasks with delay or periodic execution.
- ForkJoinPool — designed for tasks that can be broken down into subtasks (used in the Fork/Join framework), effective for parallel computations.
Differences:
- ThreadPoolExecutor is suitable for general purposes.
- ScheduledThreadPoolExecutor — for timer-based tasks.
- ForkJoinPool — for recursive parallelism.
Example of creating a ThreadPoolExecutor:
ExecutorService executor = Executors.newFixedThreadPool(4);
executor.submit(() -> System.out.println("Task completed"));
executor.shutdown();