Add withJitter(maxJitterMs) to QueryRunner.DelayStrategy

This commit is contained in:
Travis Burtrum 2017-07-03 01:20:06 -04:00
parent f24d4ed03e
commit 345a4120c8
2 changed files with 25 additions and 1 deletions

View File

@ -164,6 +164,12 @@ public class QueryRunner<T extends JdbcMapper> {
public static interface DelayStrategy {
long getDelay(int attempt);
//IFJAVA8_START
default DelayStrategy withJitter(final int maxJitterMs) {
return QueryRunner.withJitter(this, maxJitterMs);
}
//IFJAVA8_END
}
public static DelayStrategy exponentialBackoff() {
@ -231,6 +237,24 @@ public class QueryRunner<T extends JdbcMapper> {
IFJAVA6_END*/
}
public static DelayStrategy withJitter(final DelayStrategy toWrap, final int maxJitterMs) {
return
/*IFJAVA6_START
new DelayStrategy() {
@Override
public long getDelay(final int attempt) {
return
IFJAVA6_END*/
//IFJAVA8_START
(attempt) ->
//IFJAVA8_END
toWrap.getDelay(attempt) + ThreadLocalRandom.current().nextInt(maxJitterMs);
/*IFJAVA6_START
}
};
IFJAVA6_END*/
}
/*IFJAVA6_START
// terrible, I know, use java8
private static class ThreadLocalRandom {

View File

@ -19,7 +19,7 @@ public class QueryRunnerTest {
public Connection create() throws SQLException {
return QueryMapperTest.getConnection();
}
}), QueryRunner.fixedDelay(5));
}), QueryRunner.withJitter(QueryRunner.fixedDelay(5), 5));
private void testPerson(final Person expected, final String query) throws Throwable {
final Person actual =