How to add delay between API calls in CompletableFuture

Viewed 42

EDIT: I'm using java 8 so can't use executor to add delay.

I have to call an API multiple times to get a set of data. I do it using CompletableFuture as given below.Here I'm actually calling the method that calls the said API (getStockConversionResponse).

List<CompletableFuture<Void>> completableFutureList = hbbConnectionDetail.stream().map(connectionDetail -> CompletableFuture.supplyAsync(() -> getStockConversionResponse(connectionDetail, finalTeamLead, finalReceivePmsId), configuration.stockConversionExecutor()).thenAccept(stockDetailsList::add)).collect(Collectors.toList());

CompletableFuture.allOf(completableFutureList.toArray(new CompletableFuture[completableFutureList.size()])).get();

But the issue is, their backend cannot handle all the requests at once, so some requests fail. So they asked to do API calls with 1 second delay between each call.

How can I add 1 second delay between each call here?

1 Answers

You could use a circuit breaker from the excellent Resilience4j library. Essentially you wrap all remote API call into a circuit breaker, where you specify how many times a call should be retried and how long to wait in-between retries.

Example for their documentation:

// Create a CircuitBreaker (use default configuration)
CircuitBreaker circuitBreaker = CircuitBreaker.ofDefaults("backendName");

// Create a Retry with at most 3 retries and a fixed time interval between retries of 500ms
Retry retry = Retry.ofDefaults("backendName");

// Decorate your call to BackendService.doSomething() with a CircuitBreaker
Supplier<String> decoratedSupplier = CircuitBreaker
    .decorateSupplier(circuitBreaker, backendService::doSomething);

// Decorate your call with automatic retry
decoratedSupplier = Retry
    .decorateSupplier(retry, decoratedSupplier);

// Execute the decorated supplier and recover from any exception
String result = Try.ofSupplier(decoratedSupplier)
    .recover(throwable -> "Hello from Recovery").get();
Related