Best method to retry with delay in Java

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;
}

Tags:

Java