Consider adding a timeout when submiting a task
aalmiray opened this issue · comments
Take the following example
Promise<List<Person>, Throwable, Void> promise = deferredManager.when(() -> {
HttpClient client = ...
Response response = client.get(...);
return response.body();
});
This task could take a long time to resolve its value. One could argue thew task may have it's own timeout mechanism (if the HttpClient supports it), but what if it doesn't? What if the underlying task has no explicit means to issue a timeout? Consider this alternative
deferredManager.when(2, TimeUnit.SECONDS, () -> ...);
Or even
deferredManager.when(Duration.of(2, TimeUnit.SECONDS), () -> ...);
The advantage being that the amount and the time unit are contained between an immutable pair. This will require a custom Duration
class.
Perhaps the builder pattern may be applied to avoid an explosion of methods in DeferredManager
(which already contains quite a good number due to type safety concerns). What if there were a type (better name pending) with the following API:
promiseScheduler.withDelay(Duration.of(2, TimeUnit.SECONDS))
.withTimeout(Duration.of(10, SECONDS))
.when(r1, r2, ...);
This means PromiseScheduler
keeps track of state internally, and when the time is right (no pun intended) it schedules the tasks/runnables/etc using a DeferredManager impl that relies on a ScheduledExecutorService
(because this type can schedule tasks with a delay). The timeout feature could be implemented with a CountDownLatch
for example.
Btw, JDK9 added delay and timeout to CompletableFuture
.