Functionality for auto retry after exception

I made this abstract class to automatically repeat network calls if some exception is thrown.

  • I try not to retry after InterruptedException& UnknownHostException.
  • I repeat 5 times. After each failure, I perform an exponential rollback, starting with 300 ms going up 1500ms.
public abstract class AutoRetry {

  private Object dataToReturn = null;
  public Object getDataToReturn() {
    return this.dataToReturn;
  }

  public AutoRetry() {

    short retry = -1;
    while (retry++ < StaticData.NETWORK_RETRY) {

      try {
        Thread.sleep(retry * StaticData.NETWORK_CALL_WAIT);
        this.dataToReturn = doWork();
        break;
      } catch (InterruptedException | UnknownHostException e) {
        e.printStackTrace();
        this.dataToReturn = null;
        return;
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  protected abstract Object doWork() throws IOException;
}

I use it as follows:

final Object dataAfterWork = new AutoRetry() {     
  @Override
  protected Object doWork() throws IOException {
    return; //a network call which returns something
  }
}.getDataToReturn();

So is this implementation right / right?


EDIT

moved to https://codereview.stackexchange.com/questions/87686

+4
source share
2 answers

, . , Object.

Java 8 return :

public static <T> Optional<T> doWithRetry(final Supplier<T> t) {
    for (int retry = 0; retry <= StaticData.NETWORK_RETRY; ++retry) {
        try {
            Thread.sleep(retry * StaticData.NETWORK_CALL_WAIT);
            return Optional.of(t.get());
        } catch (InterruptedException | UnknownHostException e) {
            LOGGER.log(Level.SEVERE, "Call failed.", e);
            return Optional.empty();
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "Call failed. Retry.", e);
        }
    }
    LOGGER.log(Level.SEVERE, "Call failed. Retries exceeded.");
    return Optional.empty();
}

, , printStackTrace...

:

final String data = doWithRetry(() -> {
   //do stuff 
});

, @FunctionalInterface:

@FunctionalInterface
interface StuffDoer<T> {
    T doStuff() throws Exception;
}

, Exception.

Pre-Java 8:

final String data = doWithRetry(new StuffDoer<T>() {
    @Override
    public T get() throws Exception {
        return null;
    }
});
+2

Failsafe. , , , Java 8 CompletingFuture .. Ex:

RetryPolicy retryPolicy = new RetryPolicy()
  .retryOn(ConnectException.class)
  .withDelay(1, TimeUnit.SECONDS)
  .withMaxRetries(100);

// Synchronous get with retries
Connection connection = Failsafe.with(retryPolicy).get(() -> connect());

// Asynchronous get with retries
Failsafe.with(retryPolicy, executor)
  .get(() -> connect())
  .onSuccess(connection -> log.info("Connected to {}", connection))
  .onFailure(failure -> log.error("Connection attempts failed", failure));
+3

Source: https://habr.com/ru/post/1584031/


All Articles