Skip to content

Commit

Permalink
Fix delay calculation in jitter delays #2115
Browse files Browse the repository at this point in the history
Lettuce now considers overflow states and the previous delay time unit conversion is correct to avoid zero-delays.
  • Loading branch information
mp911de committed Jun 13, 2022
1 parent cc40ab7 commit d834f2c
Show file tree
Hide file tree
Showing 4 changed files with 6 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class DecorrelatedJitterDelay extends Delay implements StatefulDelay {
public Duration createDelay(long attempt) {
long value = randomBetween(base, Math.max(base, prevDelay * 3));
Duration delay = applyBounds(Duration.ofNanos(targetTimeUnit.toNanos(value)), lower, upper);
prevDelay = delay.toNanos();
prevDelay = targetTimeUnit.convert(delay.toNanos(), TimeUnit.NANOSECONDS);
return delay;
}

Expand Down
2 changes: 1 addition & 1 deletion src/main/java/io/lettuce/core/resource/Delay.java
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ public static Supplier<Delay> decorrelatedJitter(long lower, long upper, long ba
* @see ThreadLocalRandom#nextLong(long, long)
*/
protected static long randomBetween(long min, long max) {
if (min == max) {
if (min >= max) {
return min;
}
return ThreadLocalRandom.current().nextLong(min, max);
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/io/lettuce/core/resource/ExponentialDelay.java
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,8 @@ protected static long calculatePowerOfTwo(long attempt) {

if (attempt <= 0) { // safeguard against underflow
return 0L;
} else if (attempt >= 64) { // safeguard against overflow in the bitshift operation
return Long.MAX_VALUE;
} else if (attempt >= 63) { // safeguard against overflow in the bitshift operation
return Long.MAX_VALUE - 1;
} else {
return 1L << (attempt - 1);
}
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/io/lettuce/core/resource/FullJitterDelay.java
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ class FullJitterDelay extends ExponentialDelay {
public Duration createDelay(long attempt) {

long upperTarget = targetTimeUnit.convert(upper.toNanos(), TimeUnit.NANOSECONDS);
long temp = Math.min(upperTarget, base * calculatePowerOfTwo(attempt));
long upperBase = base * calculatePowerOfTwo(attempt);
long temp = Math.min(upperTarget, 0 > upperBase ? upperTarget : upperBase);
long delay = temp / 2 + randomBetween(0, temp / 2);
return applyBounds(Duration.ofNanos(targetTimeUnit.toNanos(delay)));
}
Expand Down

0 comments on commit d834f2c

Please sign in to comment.