Backend Development 15 min read

Spring Retry and Guava Retry: A Comprehensive Guide with Code Examples

This article introduces the Spring‑Retry and Guava‑Retry frameworks for Java, explains their dependencies, configuration, policies, and back‑off strategies, demonstrates both XML/annotation and programmatic usage with detailed code samples, and compares their flexibility and suitability for backend applications.

Top Architect
Top Architect
Top Architect
Spring Retry and Guava Retry: A Comprehensive Guide with Code Examples

The article provides a detailed tutorial on two Java retry frameworks—Spring‑Retry and Guava‑Retry—explaining how they enable declarative or programmatic retry of operations that may throw exceptions.

1. Spring‑Retry basic usage

First, add the Maven dependency:

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
    <version>1.2.2.RELEASE</version>
</dependency>

Define a task method that randomly throws IllegalArgumentException or RemoteAccessException and returns a boolean. Then create a RetryTemplate and configure a SimpleRetryPolicy (max attempts) and a FixedBackOffPolicy (retry interval):

RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(1000L);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(3, exceptionMap);
retryTemplate.setRetryPolicy(retryPolicy);
retryTemplate.setBackOffPolicy(backOffPolicy);

Boolean result = retryTemplate.execute(
    retryContext -> RetryDemoTask.retryTask("abc"),
    retryContext -> {
        log.info("Recovery after max attempts or non‑retryable exception");
        return false;
    }
);
log.info("Execution result:{}", result);

The RetryTemplate acts as the executor, while RetryCallback contains the business logic and RecoveryCallback handles the fallback when retries are exhausted.

Retry policies include NeverRetryPolicy , AlwaysRetryPolicy , SimpleRetryPolicy , TimeoutRetryPolicy , ExceptionClassifierRetryPolicy , CircuitBreakerRetryPolicy , and CompositeRetryPolicy . Back‑off strategies cover NoBackOffPolicy , FixedBackOffPolicy , UniformRandomBackOffPolicy , ExponentialBackOffPolicy , and ExponentialRandomBackOffPolicy .

2. Spring‑Retry annotation usage

Add @EnableRetry to the Spring Boot application class and annotate retryable methods with @Retryable , specifying exception types, max attempts, and back‑off parameters. Use @Recover for the fallback method:

@EnableRetry
public class Application { ... }

@Service
@Slf4j
public class SpringRetryDemo {
    @Retryable(value = {RemoteAccessException.class}, maxAttempts = 3,
               backoff = @Backoff(delay = 2000L, multiplier = 2))
    public boolean call(String param) {
        return RetryDemoTask.retryTask(param);
    }

    @Recover
    public boolean recover(Exception e, String param) {
        log.error("Recovery after max attempts", e);
        return false;
    }
}

A test class can autowire the service and invoke call() to observe retry behavior.

3. Guava‑Retry

Add the dependency:

<dependency>
    <groupId>com.github.rholder</groupId>
    <artifactId>guava-retrying</artifactId>
    <version>2.0.0</version>
</dependency>

Build a Retryer with RetryerBuilder , specifying exception and result predicates, wait strategy, and stop strategy:

Retryer
retryer = RetryerBuilder.
newBuilder()
    .retryIfExceptionOfType(RemoteAccessException.class)
    .retryIfResult(res -> res == false)
    .withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
    .withStopStrategy(StopStrategies.stopAfterAttempt(3))
    .build();

try {
    retryer.call(() -> RetryDemoTask.retryTask("abc"));
} catch (Exception e) {
    e.printStackTrace();
}

Guava‑Retry also supports retryIfException , retryIfRuntimeException , custom RetryListener implementations, and result‑based predicates such as Predicates.equalTo(false) or pattern matching.

4. Comparison

Both frameworks are thread‑safe and suitable for concurrent scenarios. Spring‑Retry integrates tightly with Spring and retries based on exceptions, while Guava‑Retry offers more flexible result‑based retry logic and a richer set of builder options.

backendJavaSpring Bootretry mechanismSpring RetryGuava Retry
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.