Skip to content

Commit 6437a72

Browse files
committed
Fix delay calculation in jitter delays #2115
Lettuce now considers overflow states and the previous delay time unit conversion is correct to avoid zero-delays.
1 parent 7be77cb commit 6437a72

File tree

4 files changed

+6
-5
lines changed

4 files changed

+6
-5
lines changed

src/main/java/io/lettuce/core/resource/DecorrelatedJitterDelay.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ class DecorrelatedJitterDelay extends Delay implements StatefulDelay {
6363
public Duration createDelay(long attempt) {
6464
long value = randomBetween(base, Math.max(base, prevDelay * 3));
6565
Duration delay = applyBounds(Duration.ofNanos(targetTimeUnit.toNanos(value)), lower, upper);
66-
prevDelay = delay.toNanos();
66+
prevDelay = targetTimeUnit.convert(delay.toNanos(), TimeUnit.NANOSECONDS);
6767
return delay;
6868
}
6969

src/main/java/io/lettuce/core/resource/Delay.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -325,7 +325,7 @@ public static Supplier<Delay> decorrelatedJitter(long lower, long upper, long ba
325325
* @see ThreadLocalRandom#nextLong(long, long)
326326
*/
327327
protected static long randomBetween(long min, long max) {
328-
if (min == max) {
328+
if (min >= max) {
329329
return min;
330330
}
331331
return ThreadLocalRandom.current().nextLong(min, max);

src/main/java/io/lettuce/core/resource/ExponentialDelay.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -91,8 +91,8 @@ protected static long calculatePowerOfTwo(long attempt) {
9191

9292
if (attempt <= 0) { // safeguard against underflow
9393
return 0L;
94-
} else if (attempt >= 64) { // safeguard against overflow in the bitshift operation
95-
return Long.MAX_VALUE;
94+
} else if (attempt >= 63) { // safeguard against overflow in the bitshift operation
95+
return Long.MAX_VALUE - 1;
9696
} else {
9797
return 1L << (attempt - 1);
9898
}

src/main/java/io/lettuce/core/resource/FullJitterDelay.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,8 @@ class FullJitterDelay extends ExponentialDelay {
5353
public Duration createDelay(long attempt) {
5454

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

0 commit comments

Comments
 (0)