java 43 lines · 8 steps

Exponential backoff retry in Java

A reusable executor retries a failing operation with exponentially growing, jittered delays until it succeeds or exhausts its attempts.

Explained by highlit
1public final class RetryExecutor {
2 
3 private final int maxAttempts;
4 private final Duration initialDelay;
5 private final double multiplier;
6 private final Duration maxDelay;
7 
8 public RetryExecutor(int maxAttempts, Duration initialDelay, double multiplier, Duration maxDelay) {
9 this.maxAttempts = maxAttempts;
10 this.initialDelay = initialDelay;
11 this.multiplier = multiplier;
12 this.maxDelay = maxDelay;
13 }
14 
15 public <T> T execute(Callable<T> operation) throws Exception {
16 Exception lastFailure = null;
17 long delayMillis = initialDelay.toMillis();
18 
19 for (int attempt = 1; attempt <= maxAttempts; attempt++) {
20 try {
21 return operation.call();
22 } catch (Exception e) {
23 lastFailure = e;
24 if (attempt == maxAttempts) {
25 break;
26 }
27 
28 long jitter = ThreadLocalRandom.current().nextLong(delayMillis / 2 + 1);
29 long sleep = Math.min(delayMillis + jitter, maxDelay.toMillis());
30 try {
31 Thread.sleep(sleep);
32 } catch (InterruptedException ie) {
33 Thread.currentThread().interrupt();
34 throw ie;
35 }
36 
37 delayMillis = (long) (delayMillis * multiplier);
38 }
39 }
40 
41 throw new IllegalStateException("Operation failed after " + maxAttempts + " attempts", lastFailure);
42 }
43}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Exponential backoff spreads retries over widening intervals so a struggling dependency gets room to recover.
  2. 2Adding random jitter prevents many clients from retrying in lockstep and hammering a service simultaneously.
  3. 3Restoring the interrupt flag and rethrowing on InterruptedException keeps the operation responsive to cancellation.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Exponential backoff retry in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code