Skip to content

Support WaitStrategy.randomExponentialWait() #28

@ceefour

Description

@ceefour

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions