GatewayThrottler { public void handleCall(int transientErrors) { if (transientErrors > 0) { backOffTimeMs = Math.min(maxSleepTimeMs, backOffTimeMs + distribute(100)); } else { backOffTimeMs = Math.max(0, backOffTimeMs - distribute(10)); } sleepMs(backOffTimeMs); } GatewayThrottler(long maxSleepTimeMs); void handleCall(int transientErrors); int distribute(int expected);  }
@Test public void noSleepOnNormalCase() { gatewayThrottler.handleCall(0); gatewayThrottler.handleCall(0); assertThat(lastSleepValue, is(0L)); }
@Test public void increastingSleepTime() { gatewayThrottler.handleCall(1); long sleepTime1 = lastSleepValue; gatewayThrottler.handleCall(1); long sleepTime2 = lastSleepValue; assertTrue(sleepTime1 > 0); assertTrue(sleepTime2 > sleepTime1); int x; for (x = 0 ; x < 10000; x++) { long prevSleepTime = lastSleepValue; gatewayThrottler.handleCall(1); if (prevSleepTime == lastSleepValue) break; } assertTrue(x < 5000); for (x = 0 ; x < 10000; x++) { gatewayThrottler.handleCall(0); if (lastSleepValue == 0) break; } assertTrue(x < 5000); }