guava-retrying icon indicating copy to clipboard operation
guava-retrying copied to clipboard

Support WaitStrategy.randomExponentialWait()

Open ceefour opened this issue 10 years ago • 4 comments
trafficstars

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;
    }
}

ceefour avatar Dec 04 '14 12:12 ceefour

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

rholder avatar May 03 '15 00:05 rholder

Any plan to release the random exponential wait strategy?

alvinlin123 avatar Sep 09 '16 21:09 alvinlin123

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

JensRantil avatar Sep 11 '16 09:09 JensRantil

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

alvinlin123 avatar Sep 21 '16 01:09 alvinlin123