Home > Enterprise >  CompletableFuture - orTimeout
CompletableFuture - orTimeout

Time:09-14

What is the advantage of using the orTimeout and get instead of just get?

CompletableFuture<T> cf = ....;

cf.orTimeout(10, TimeUnit.SECONDS).get()

over

cf.get(10, TimeUnit.SECONDS);

CodePudding user response:

orTimeout returns a new CompletableFuture, and it can be applied in a chain or at some other lower level than the final consumer:

@AllArgsConstructor
class ResourceLimiter implements ServiceApi {
  ServiceApi delegate;

  @Override
  CompletableFuture<Result> findResult(ServiceInput input) {
    return delegate.findResult(input).orTimeout(10, SECONDS);
  }
}


@AllArgsConstructor
class IHaveLotsOfTime {
  ServiceApi service;

  void checkResultsSlowly() {
    service.get(12, HOURS);
  }
}

CodePudding user response:

After checking the source, I see that orTimeout cancels the CompletableFuture after the timeout whereas get does not cancel.

public CompletableFuture<T> orTimeout(long timeout, TimeUnit unit) {
    if (unit == null)
        throw new NullPointerException();
    if (result == null)
        whenComplete(new Canceller(Delayer.delay(new Timeout(this),
                                                 timeout, unit)));
    return this;
}
  •  Tags:  
  • java
  • Related