218. Hooking task state
Starting with JDK 19, we can rely on Future.state()
. This method computes the state of a Future
based on the well-known get()
, isDone()
, and isCancelled()
, returning a Future.State
enum entry, as follows:
CANCELLED
– the task was canceled.FAILED
– the task was completed exceptionally (with an exception).RUNNING
– the task is still running (has not been completed).SUCCESS
– the task was completed normally with a result (no exception).
In the following snippet of code, we analyze the state of loading the testing team members and act accordingly:
public static TestingTeam buildTestingTeam()
throws InterruptedException {
List<String> testers = new ArrayList<>();
try (ExecutorService executor
= Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<String>> futures = executor.invokeAll(
List.of(() -> fetchTester(Integer.MAX_VALUE)...