I need to submit a task in an async framework I\'m working on, but I need to catch for exceptions, and retry the same task multiple times before \"aborting\".
The code I
Here is an approach that will work for any CompletionStage
subclass and does not return a dummy CompletableFuture
that does nothing more than wait to get updated by other futures.
/**
* Sends a request that may run as many times as necessary.
*
* @param request a supplier initiates an HTTP request
* @param executor the Executor used to run the request
* @return the server response
*/
public CompletionStage asyncRequest(Supplier> request, Executor executor)
{
return retry(request, executor, 0);
}
/**
* Sends a request that may run as many times as necessary.
*
* @param request a supplier initiates an HTTP request
* @param executor the Executor used to run the request
* @param tries the number of times the operation has been retried
* @return the server response
*/
private CompletionStage retry(Supplier> request, Executor executor, int tries)
{
if (tries >= MAX_RETRIES)
throw new CompletionException(new IOException("Request failed after " + MAX_RETRIES + " tries"));
return request.get().thenComposeAsync(response ->
{
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL)
return retry(request, executor, tries + 1);
return CompletableFuture.completedFuture(response);
}, executor);
}