Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

ExecutorService.close()

Closes the pool and waits for all tasks; called automatically by try-with-resources.

Available since: Java 19

Syntax

default void close()

Examples

After the try block all tasks are guaranteed to be done:

void main() {
    var results = new ConcurrentLinkedQueue<Integer>();
    try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
        for (int i = 1; i <= 3; i++) {
            int n = i;
            executor.submit(() -> results.add(n * 10));
        }
    }
    IO.println(results.stream().sorted().toList());
}

Output:

[10, 20, 30]

Notes

close() calls shutdown() and waits for all tasks to finish. The order in which the tasks ran is not defined, so the example sorts the result before printing it.

See also

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.