Skip to content

Instantly share code, notes, and snippets.

@DoumanAsh
Created June 17, 2021 09:18
Show Gist options
  • Save DoumanAsh/0a37f4f91c8a6f51e7369c9d59d0abc7 to your computer and use it in GitHub Desktop.
Save DoumanAsh/0a37f4f91c8a6f51e7369c9d59d0abc7 to your computer and use it in GitHub Desktop.
import com.datastax.driver.core.exceptions.NoHostAvailableException;
import io.lettuce.core.RedisCommandExecutionException;
import org.slf4j.Logger;
import java.util.concurrent.Callable;
public class ExponentialBackoff {
private final long delay;
private final long maxAttempts;
private final Logger logger;
private final long MAX_WAIT_TIME_MS = 60000;
public ExponentialBackoff(Logger logger, long delay, long maxAttempts) {
this.logger = logger;
this.delay = delay;
this.maxAttempts = maxAttempts;
}
@SuppressWarnings("InfiniteLoopStatement")
public void execute(Callable<Void> task) throws Exception {
int attempt = 0;
while(true) {
try {
task.call();
attempt = 0;
Thread.sleep(this.delay);
} catch (NoHostAvailableException | RedisCommandExecutionException error) {
if (attempt == this.maxAttempts) {
this.logger.error("Long connectivity issue is ongoing");
} else {
attempt += 1;
}
long waitTime = this.calculateWaitTime(attempt);
this.logger.info("Retrying in {}ms...", waitTime);
Thread.sleep(waitTime);
}
}
}
private long calculateWaitTime(int attempt) {
final long wait = ((long) Math.pow(2, attempt)) * Math.max(this.delay, 1);
return Math.min(wait, MAX_WAIT_TIME_MS);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment