Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best method to retry with delay in Java

Tags:

java

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;
}
like image 248
annedroiid Avatar asked Oct 06 '16 00:10

annedroiid


2 Answers

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.

like image 95
Gonzalo Matheu Avatar answered Sep 28 '22 07:09

Gonzalo Matheu


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;
}
like image 21
Scary Wombat Avatar answered Sep 28 '22 08:09

Scary Wombat