Mastering Retry Logic in Java: Spring‑Retry vs Guava‑Retry
This article explains how to implement robust retry mechanisms in Java applications by comparing Spring‑Retry's declarative exception‑based approach with Guava‑Retry's flexible result‑oriented strategy, covering dependencies, configuration, policies, back‑off options, annotation usage, and practical code examples.
Spring‑Retry provides declarative retry support for Spring applications, suitable for batch processing, integration, and Hadoop. After adding the Maven dependency, you can create a task method that randomly throws exceptions or returns values, then use RetryTemplate to configure a SimpleRetryPolicy (max attempts) and a FixedBackOffPolicy (retry interval). The template executes the task via execute, requiring a RetryCallback for the main logic and a RecoveryCallback for fallback when retries are exhausted or a non‑retryable exception occurs.
Retry Policies
NeverRetryPolicy : no retries.
AlwaysRetryPolicy : unlimited retries (risk of infinite loop).
SimpleRetryPolicy : fixed number of attempts (default 3).
TimeoutRetryPolicy : retries within a time limit.
ExceptionClassifierRetryPolicy : different policies per exception type.
CircuitBreakerRetryPolicy : adds open/close timeouts and a delegate.
CompositeRetryPolicy : combines multiple policies (optimistic or pessimistic).
Back‑off Strategies
NeverBackOffPolicy : immediate retry.
FixedBackOffPolicy : fixed sleep period (default 1 s, configurable via sleeper and backOffPeriod).
UniformRandomBackOffPolicy : random sleep between minBackOffPeriod and maxBackOffPeriod.
ExponentialBackOffPolicy : exponential increase using initialInterval, maxInterval, and multiplier.
ExponentialRandomBackOffPolicy : exponential back‑off with random jitter.
When using Spring‑Boot, enable retry with @EnableRetry and annotate methods with @Retryable (specifying exception types, max attempts, and back‑off) and recovery methods with @Recover. Example service code demonstrates a method that retries on RemoteAccessException with a 2‑second initial delay that doubles each attempt.
Guava‑Retry
Guava‑Retry (artifact guava-retrying) offers a thread‑safe retryer built around java.util.concurrent.Callable. Using RetryerBuilder, you can define retry conditions based on exception types ( retryIfExceptionOfType) or result values ( retryIfResult), set a fixed wait strategy, and limit attempts with a stop strategy.
Retryer<Boolean> retryer = RetryerBuilder.<Boolean>newBuilder()
.retryIfExceptionOfType(RemoteAccessException.class)
.retryIfResult(res -> res == false)
.withWaitStrategy(WaitStrategies.fixedWait(3, TimeUnit.SECONDS))
.withStopStrategy(StopStrategies.stopAfterAttempt(3))
.build();The retryer is invoked via retryer.call(() -> RetryDemoTask.retryTask("abc")). Guava‑Retry also supports listeners ( RetryListener) to log each failed attempt.
Comparison
Both frameworks are thread‑safe and suitable for concurrent retry scenarios. Spring‑Retry integrates tightly with the Spring ecosystem and retries based on declared exceptions, while Guava‑Retry provides more flexible criteria, including result‑based retries and richer back‑off configurations. In practice, Guava‑Retry often requires less boilerplate for simple use cases.
Overall, choose Spring‑Retry when you need seamless Spring integration and exception‑driven retries; choose Guava‑Retry when you prefer result‑oriented logic and more granular control over retry policies.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Architect Essentials
Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
