QR code

How to Retry Java Method Call on Exception

  • comments

aop Javajava Mavenjcabi

badge

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):

  • Executing JDBC SELECT statements

  • Loading data from HTTP, S3, FTP, etc resources

  • Uploading data over the network

  • Fetching data through RESTful stateless API-s

The project is in GitHub.

sixnines availability badge   GitHub stars