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
- ExecutorService.shutdown() — Closes the pool to new tasks and lets accepted ones finish.
- try-with-resources — A `try` block that closes opened resources automatically — files, connections, streams.
- ExecutorService — A service that runs tasks on a pool of threads.
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.