This is a mobile version, full one is here.

Yegor Bugayenko
15 August 2014

How to Retry Java Method Call on Exception

If you have a method that fails occasionally and you want to retry it a few times before throwing an exception. @RetryOnFailure from jcabi-aspects can help. For example, if you’re downloading the following web page:

@RetryOnFailure(
  attempts = 3,
  delay = 10,
  unit = TimeUnit.SECONDS
)
public String load(URL url) {
  return url.openConnection().getContent();
}

This method call will throw an exception only after three failed executions with a ten seconds interval between them.

This post explains how jcabi-aspects works with binary weaving. This mechanism integrates AspectJ with your code.

When method load() from the example above is called, this is what is happening behind the scene (pseudo-code):

while (attempts++ < 3) {
  try {
    return original_load(url);
  } catch (Throwable ex) {
    log("we failed, will try again in 10 seconds");
    sleep(10);
  }
}

This approach may be very useful in the following situations (based on my experience):

The project is in GitHub.