Skip to content

Commit

Permalink
#48 RetransmissionBackOff: add configurable random factory
Browse files Browse the repository at this point in the history
  • Loading branch information
szysas committed Apr 24, 2023
1 parent ca83ef3 commit 07d2c7a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ static RetransmissionBackOff ofFixed(Duration interval) {
}

static RetransmissionBackOff ofExponential(Duration first, int maxAttempts) {
return ofExponential(first, maxAttempts, CoapConstants.ACK_RANDOM_FACTOR);
}

static RetransmissionBackOff ofExponential(Duration first, int maxAttempts, float randomFactor) {
require(randomFactor >= 1);
require(maxAttempts >= 0);
final Random rnd = new Random();
long firstMs = first.toMillis();

Expand All @@ -50,7 +56,7 @@ static RetransmissionBackOff ofExponential(Duration first, int maxAttempts) {
return Duration.ZERO;
}

float rndFactor = 1 + (CoapConstants.ACK_RANDOM_FACTOR - 1) * rnd.nextFloat();
float rndFactor = 1 + (randomFactor - 1) * rnd.nextFloat();
return Duration.ofMillis((long) (firstMs * rndFactor * (1L << (attempt - 1))));
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,4 +111,22 @@ public void singleTimeoutTest() {
assertThrows(IllegalArgumentException.class, () -> singleTimeout.next(0));
assertThrows(IllegalArgumentException.class, () -> singleTimeout.next(-1));
}

@Test
public void retransmission_with_custom_random_factor() {
RetransmissionBackOff backOff = RetransmissionBackOff.ofExponential(ofSeconds(2), 2, 1.0f);

assertEquals(2000, backOff.next(1).toMillis());
assertEquals(4000, backOff.next(2).toMillis());
}

@Test
void should_fail_with_wrong_parameters() {
assertThrows(IllegalArgumentException.class, () -> RetransmissionBackOff.ofExponential(ofSeconds(2), 2, 0.99f));
assertThrows(IllegalArgumentException.class, () -> RetransmissionBackOff.ofExponential(ofSeconds(2), 2, 0f));
assertThrows(IllegalArgumentException.class, () -> RetransmissionBackOff.ofExponential(ofSeconds(2), 2, -1.321f));


assertThrows(IllegalArgumentException.class, () -> RetransmissionBackOff.ofExponential(ofSeconds(2), -1, 2f));
}
}

0 comments on commit 07d2c7a

Please sign in to comment.