Created
August 26, 2021 13:09
-
-
Save cicorias/2091925aa1feb5b089127c4f97804b85 to your computer and use it in GitHub Desktop.
Exponential backoff in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Main { | |
public static void main(String[] args) { | |
System.out.println("Hello world!"); | |
retry("foo"); | |
} | |
static void retry(String... args) { | |
boolean retry = true; | |
int attempts = 0; | |
int maxAttempts = 10; | |
int maxWaitTime = 5000; | |
do { | |
long waitTime = Math.min(getWaitTimeExp(attempts), maxWaitTime); | |
System.out.print(waitTime + "\n"); | |
try { | |
Thread.sleep(waitTime); | |
//NOTE: call the task that might fail. | |
longOperation(); | |
retry = false; | |
} catch (Exception e) { | |
//TODO: handle exception | |
} | |
} while (retry && attempts++ < maxAttempts); | |
} | |
static void longOperation() throws Exception { | |
try { | |
Thread.sleep(100); | |
throw new Exception("bad record"); | |
} catch (InterruptedException e) { | |
// TODO: handle exception | |
} | |
} | |
/* | |
* Returns the next wait interval, in milliseconds, using an exponential backoff | |
* algorithm. | |
*/ | |
public static long getWaitTimeExp(int retryCount) { | |
if (0 == retryCount) { | |
return 0; | |
} | |
long waitTime = ((long) Math.pow(2, retryCount) * 100L); | |
return waitTime; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment