221. Introducing ShutdownOnSuccess
In the previous problem, we introduced StructuredTaskScope
and used it to solve a task via a single virtual thread (a single Subtask
). Basically, we fetched the tester with ID 1 from our server (we had to wait until this one was available). Next, let’s assume that we still need a single tester, but not mandatorily the one with ID 1. This time, it could be any of IDs 1, 2, or 3. We simply take the first one that is available from these three, and we cancel the other two requests.
Especially for such scenarios, we have an extension of StructuredTaskScope
called StructuredTaskScope.ShutdownOnSuccess
. This scope is capable of returning the result of the first task that completes successfully and interrupts the rest of the threads. It follows the “invoke any” model and can be used as follows:
public static TestingTeam buildTestingTeam()
throws InterruptedException, ExecutionException {
try (ShutdownOnSuccess scope...