In my program I call a method that can either return a value or "", and basically I want it to retry looking up the value 3 times with a delay of 1 second inbetween each try until it gets a value or the tries are finished.
This is what I currently have but I feel like this solution is pretty gross, particularly having to put the try/catch around the sleep. Does anyone know of a better way to retry with a delay?
public void method(String input){
String value = getValue(input);
int tries = 0
while (value.equals("") && tries < 3){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
log.error("Thread interrupted");
}
value = getValue(input);
tries += 1;
}
return value;
}
Fixed Poll Interval feature of awaitility might help:
Awaitility.with()
.pollInterval(1, SECONDS)
.atMost(3, SECONDS)
.await()
.until(() -> ("" != getValue(input)));
It offers a fluent interface for synchronizing asynchronous operations.
At the end of the day you can not get around the fact that in needs to catch the Exception
What you can do though is hide it by putting in in your own method
public static void mySleep (int val) {
try {
TimeUnit.SECONDS.sleep(val);
} catch (InterruptedException e) {
log.error("Thread interrupted");
}
}
So you main
function becomes cleaner as
while (value.equals("") && tries < 3){
mySleep (1);
value = getValue(input);
tries += 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With