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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Exponential backoff spreads retries over widening intervals so a struggling dependency gets room to recover.
- 2Adding random jitter prevents many clients from retrying in lockstep and hammering a service simultaneously.
- 3Restoring the interrupt flag and rethrowing on InterruptedException keeps the operation responsive to cancellation.
Related explainers
java
@Component public class RegionCacheWarmer implements SmartInitializingSingleton { private static final Logger log = LoggerFactory.getLogger(RegionCacheWarmer.class);
Warming a Spring cache at startup
caching
startup-hook
dependency-injection
Intermediate
7 steps
go
package breaker import ( "errors"
How a circuit breaker works in Go
circuit-breaker
state-machine
concurrency
Intermediate
8 steps
java
public final class EmailNormalizer { private static final Pattern EMAIL_PATTERN = Pattern.compile( "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$"
Normalizing email addresses in Java
validation
regex
normalization
Intermediate
8 steps
ruby
module UniqueJob extend ActiveSupport::Concern class_methods do
Deduplicating Active Job enqueues in Rails
concurrency
idempotency
caching
Advanced
9 steps
java
@RestController @RequestMapping("/api/products") @RequiredArgsConstructor public class ProductBatchController {
Batch JSON Merge Patch in Spring
json-merge-patch
rest-api
partial-update
Intermediate
8 steps
java
public class TimedFetchService { private final ExecutorService executor = Executors.newFixedThreadPool(8); private final HttpClient httpClient = HttpClient.newHttpClient();
Enforcing HTTP timeouts with a Future
concurrency
timeouts
thread-pool
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/exponential-backoff-retry-in-java-explained-java-0861/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.