From 345a4120c8e60c58efc0628d9bc140866741e132 Mon Sep 17 00:00:00 2001 From: moparisthebest Date: Mon, 3 Jul 2017 01:20:06 -0400 Subject: [PATCH] Add withJitter(maxJitterMs) to QueryRunner.DelayStrategy --- .../com/moparisthebest/jdbc/QueryRunner.java | 24 +++++++++++++++++++ .../moparisthebest/jdbc/QueryRunnerTest.java | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/common/src/main/java/com/moparisthebest/jdbc/QueryRunner.java b/common/src/main/java/com/moparisthebest/jdbc/QueryRunner.java index 76ebcd1..2170360 100644 --- a/common/src/main/java/com/moparisthebest/jdbc/QueryRunner.java +++ b/common/src/main/java/com/moparisthebest/jdbc/QueryRunner.java @@ -164,6 +164,12 @@ public class QueryRunner { 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 { 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 { diff --git a/querymapper/src/test/java/com/moparisthebest/jdbc/QueryRunnerTest.java b/querymapper/src/test/java/com/moparisthebest/jdbc/QueryRunnerTest.java index 477729f..6f173f0 100644 --- a/querymapper/src/test/java/com/moparisthebest/jdbc/QueryRunnerTest.java +++ b/querymapper/src/test/java/com/moparisthebest/jdbc/QueryRunnerTest.java @@ -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 =