ExecutorService
A service that runs tasks on a pool of threads.
Available since: Java 1.5
Syntax
public interface ExecutorService extends Executor, AutoCloseableExamples
Tasks on a pool and collecting results:
void main() throws Exception {
try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
List<Future<Integer>> results = new ArrayList<>();
for (int n = 1; n <= 5; n++) {
int x = n;
results.add(pool.submit(() -> x * x));
}
for (Future<Integer> f : results) {
IO.print(f.get() + " ");
}
IO.println("");
}
}Output:
1 4 9 16 25Notes
A pool separates what to do (the task) from where to run it (the threads). It is created with the Executors factories. Since Java 19 the service implements AutoCloseable, so it is handy in try-with-resources: leaving the block waits for all tasks. Otherwise the pool must be closed with shutdown(), or the program may not exit.
See also
- Executors.newFixedThreadPool() — Creates a pool with a given number of threads.
- ExecutorService.submit() — Sends a task to the pool and immediately returns a `Future` for its result.
- ExecutorService.close() — Closes the pool and waits for all tasks; called automatically by try-with-resources.
- Future.get() — Waits for a task to finish and returns its result.
Related recipes
In the tutorial
- Thread pools and ExecutorService — ExecutorService in Java — thread pools, submit, Callable and Future, invokeAll, handling errors in tasks, timeouts and closing the pool.