Skip to content

Commit

Permalink
fix: do not integer overflow when attempt gets too high (#16)
Browse files Browse the repository at this point in the history
* fix: do not integer overflow when attempt gets too high

* Update ExponentialBackoffTest.java
  • Loading branch information
lizthegrey authored Feb 15, 2022
1 parent 66cc8f7 commit f59bcd6
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ final class ExponentialBackoff {

final int error() {
attempt += 1;
final int multiplier = (int) Math.pow(2, attempt);
final int upper = Math.min(cap, base * multiplier);
return random.nextInt(upper);
int multiplier = cap / base;
if ((multiplier >> attempt) > 0) {
multiplier = 1 << attempt;
}
return random.nextInt(base * multiplier);
}

final void reset() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ void test() {
assertEquals(4_000, exponentialBackoff.error());
assertEquals(8_000, exponentialBackoff.error());
assertEquals(16_000, exponentialBackoff.error());
assertEquals(30_000, exponentialBackoff.error());
assertEquals(30_000, exponentialBackoff.error());
for (int i = 0; i < 100; i++) {
assertEquals(30_000, exponentialBackoff.error());
}
}
}

0 comments on commit f59bcd6

Please sign in to comment.