229. Assembling StructuredTaskScope instances with timeout
Let’s continue our journey from Problem 228 by assuming that the ridesharing service should be implemented with a timeout/deadline. In other words, if any of the ridesharing servers don’t answer in 10 milliseconds, then we abort the request and report the thrown TimeoutException
via a meaningful message to the user.
This means that instead of scope.join()
, which waits indefinitely, we should use joinUntil(Instant deadline)
, which waits only for the given deadline
before throwing a TimeoutException
. So, the fetchRidesharingOffers()
method should be modified as follows:
public static RidesharingOffer fetchRidesharingOffers(
String loc, String dest)
throws InterruptedException, TimeoutException {
try (StructuredTaskScope scope
= new StructuredTaskScope<RidesharingOffer>()) {
...
scope.joinUntil(Instant.now().plusMillis(10));
...
}
}
By simply simulating a delay...