Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

ExecutorService

A service that runs tasks on a pool of threads.

Available since: Java 1.5

Syntax

public interface ExecutorService extends Executor, AutoCloseable

Examples

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 25

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.