1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.util.Random;
import java.util.concurrent.TimeUnit;
class ProbabilisticExponentialBackoffPoller {
public Object[] poll(
final TimeUnit timeUnit,
final int initialDelay,
final int maxTotalDelay,
final double delayResetProbability)
throws InterruptedException {
final Random random = new Random();
Object[] messages = readMessages();
int currentDelay = initialDelay;
int totalDelay = 0;
while (messages.length == 0 && totalDelay <= maxTotalDelay) {
System.out.printf("Sleeping for %d %s\n", currentDelay, timeUnit);
timeUnit.sleep(currentDelay);
totalDelay += currentDelay;
currentDelay *= 2;
if (delayResetProbability > random.nextDouble()) {
System.out.println("Resetting delay interval");
currentDelay = initialDelay;
}
messages = readMessages();
}
return messages;
}
private Object[] readMessages() {
return new Object[0];
}
}
public class Main {
public static void main(String args[]) throws Exception {
new ProbabilisticExponentialBackoffPoller().poll(TimeUnit.MILLISECONDS, 2, 60, 0.42);
}
}
Enter to Rename, Shift+Enter to Preview