rholder / guava-retrying

This is a small extension to Google's Guava library to allow for the creation of configurable retrying strategies for an arbitrary function call, such as something that talks to a remote service with flaky uptime.
Apache License 2.0
1.44k stars 275 forks source link

Support WaitStrategy.randomExponentialWait() #28

Open ceefour opened 9 years ago

ceefour commented 9 years ago

A combination between randomWait() and exponentialWait(), as described in http://en.wikipedia.org/wiki/Exponential_backoff , where the exponential wait time is used as the random range.

This is how I do it:

@Immutable
private static final class RandomExponentialWaitStrategy implements WaitStrategy {
    private static final Random RANDOM = new Random();
    private final long multiplier;
    private final long maximumWait;

    public RandomExponentialWaitStrategy(long multiplier,
                                   long maximumWait) {
        Preconditions.checkArgument(multiplier > 0L, "multiplier must be > 0 but is %d", multiplier);
        Preconditions.checkArgument(maximumWait >= 0L, "maximumWait must be >= 0 but is %d", maximumWait);
        Preconditions.checkArgument(multiplier < maximumWait, "multiplier must be < maximumWait but is %d", multiplier);
        this.multiplier = multiplier;
        this.maximumWait = maximumWait;
    }

    @Override
    public long computeSleepTime(int previousAttemptNumber, long delaySinceFirstAttemptInMillis) {
        long upperExp = Math.round(Math.pow(2, previousAttemptNumber));
        long exp = Math.abs(RANDOM.nextLong()) % upperExp;
        long result = Math.round(multiplier * exp);
        if (result > maximumWait) {
            result = maximumWait;
        }
        return result >= 0L ? result : 0L;
    }
}
rholder commented 9 years ago

I would accept a PR for this with some testing on the expected wait time ranges that should pop out.

alvinlin123 commented 8 years ago

Any plan to release the random exponential wait strategy?

JensRantil commented 8 years ago

@alvinlin123 It's really easy to implement it. Feel free to submit a pull request.

alvinlin123 commented 8 years ago

@JensRantil I thought there is already a pull request there that have not been merged? https://github.com/rholder/guava-retrying/pull/50