Sometimes the difference between a flaky system and a reliable one is just a few lines of retry logic. Network calls fail, APIs timeout, and transient issues happen more often than we’d like to admit.
Instead of scattering retry logic everywhere, here’s a small reusable utility with exponential backoff:
// Simple retry utility with exponential backoff
public static T retry(Supplier task, int maxAttempts) {
int attempt = 0;
long delay = 200;
while (true) {
try {
return task.get();
} catch (Exception e) {
if (++attempt >= maxAttempts) {
throw e;
}
try {
Thread.sleep(delay);
} catch (InterruptedException ignored) {}
delay *= 2; // exponential backoff
}
}
}
Why this works:
Handles temporary failures (network hiccups, rate limits)
Exponential backoff reduces pressure on downstream services
Keeps your business logic clean and focused
Usage example:
String result = retry(() -> apiCall(), 3);
Simple, effective, and saves you from a lot of random headaches in production.