Java 9 introduced many new methods in the CompletableFuture API that support execution timeouts. For example:

public CompletableFuture<T> orTimeout​(long timeout, TimeUnit unit);

public CompletableFuture<T> completeOnTimeout​(T value, long timeout, TimeUnit unit);

More can be found in the documentation.

These methods take a long and a TimeUnit as arguments. Is there a specific reason it has been done so? Wouldn't Duration be a better choice here?

public CompletableFuture<T> orTimeout​(Duration duration);

public CompletableFuture<T> completeOnTimeout​(T value, Duration duration);
  • 1
    My guess is that, since Duration was just introduced in Java 8, they either didn't think of it, or decided it was "too new" and stuck with a more traditional and usual implementation.
    – user949300
    Oct 17 '20 at 18:23
  • 3
    I would guess for the reason @user949300 said, and also much of the rest of the Java concurrency API uses TimeUnit (because Duration didn't exist at that point) so this way it's consistent.
    – just me
    Oct 17 '20 at 21:30
  • I feel that overloaded methods with both styles would have been better. That is how you slowly push the users towards newer (and objectively better) API. Oct 19 '20 at 5:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.