retry
is a small, dependency-free Java library for configuring retry strategies. It is heavily inspired by guava-retrying
, without its dependency on Guava.
retry
is available via Maven Central. To include it in a Gradle project, add the following dependency:
compile "org.joeyb.retry:retry:$retryVersion"
A Retry<V>
instance is configured with a particular retry strategy, and can be used by passing a Callable<V>
to its call
method:
Retry<V> retry = ...
V result = retry.call(() -> service.performUnreliableRequest());
The retry strategy is dictated by 5 basic components:
The acceptance strategy (defined by the Accept
interface) is used to specify whether or not the result from an attempted execution of the underlying Callable<V>
should be accepted. For example, Accepts.any()
returns an Accept
instance that accepts any value.
The attempt listener (defined as a Consumer<Attempt<V>>
) is used to give the consumer a notification of failed attempts. This is useful for logging failures or keeping metrics of failed attempt counts.
The blocking strategy (defined by the Block
interface) is used to specify how the retryer should block its thread while waiting for the next attempt. The default is a Thread.sleep()
-based implementation, which should be sufficient for most use-cases.
The stopping strategy (defined by the Stop
interface) is used to specify when the retryer should give up. The Stops
class provides some common implementations, including stopping based on a maximum number of attempts or a maximum time since start.
The wait strategy (defined by the Wait
interface) is used to specify how long the retryer should wait between each attempt.
The Retry<V>
class provides a fluent builder for constructing retry strategies. For example, you can build a simple retry strategy that retries indefinitely, with no waiting between attempts, until it gets back a non-null value like this:
Retry<Long> retry = Retry.<Long>newBuilder()
.acceptNonNullResult()
.build()