Commit 787f8429 authored by Bhargavi Ghanta's avatar Bhargavi Ghanta

Add RetryUtility with exponential backoff logic

parent 383cb52d
......@@ -2,15 +2,26 @@ import java.util.concurrent.Callable;
public class RetryUtility {
/**
* Retries a task up to maxRetries with exponential backoff.
*
* @param task The task to execute.
* @param maxRetries Number of retry attempts.
* @param initialDelayMillis Initial delay before retrying (in milliseconds).
* @return The result of the task if successful.
* @throws Exception If all retry attempts fail.
*/
public static <T> T retry(Callable<T> task, int maxRetries, long initialDelayMillis) throws Exception {
int attempt = 0;
while (true) {
try {
return task.call(); // Try to execute the task
return task.call(); // Attempt the task
} catch (Exception e) {
attempt++;
if (attempt > maxRetries) {
throw new Exception("All retry attempts failed", e);
throw new Exception("All retry attempts failed after " + maxRetries + " tries", e);
}
long backoffTime = initialDelayMillis * (1L << (attempt - 1)); // Exponential backoff
......@@ -25,12 +36,12 @@ public class RetryUtility {
public static void main(String[] args) {
try {
String result = retry(() -> {
// Simulate network call that fails randomly
// Simulate an unreliable remote service
if (Math.random() < 0.7) {
throw new RuntimeException("Network error!");
}
return "Success!";
}, 5, 1000); // Retry up to 5 times, starting with 1 second delay
}, 5, 1000); // Try up to 5 times, starting with 1 second backoff
System.out.println("Final Result: " + result);
} catch (Exception e) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment