3

I have two classes A & B , like this:

class A {
    public Integer fetchMax() {
       // Make a network call & return result
    } 
}

class B {
    public Double fetchPercentile(Integer input) {
        // Make a network call & return result
    } 
}

Now I need to provide retry mechanism for both methods fetchMax() & fetchPercentile(Integer). I want to provide this behaviour using a helper class, where the retry method which can take instance of (A or B), method-name and method-arguments. The retry would basically do reattempts on the provided method of the object.

Something like this:

class Retry {
     public static R retry(T obj, Function<T, R> method,  Object... arguments) {
           // Retry logic
           while(/* retry condition */)
           {
                obj.method(arguments);
           }
     }
}
Mohitt
  • 2,957
  • 3
  • 29
  • 52

1 Answers1

9

Just take a Callable as argument:

public static <R> R retry(Callable<R> action) {
    // Retry logic
    while(/* retry condition */) {
        action.call();
    }
}

And call it this way:

Retry.retry(() -> a.fetchMax());
Retry.retry(() -> b.fetchPercentile(200));

You might want to use, or get inspiration from guava-retrying, a small extension to Google's Guava library to allow for the creation of configurable retrying strategies (disclaimer: I'm the original author).

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Throughout the question I couldn't just see what was required there and if it related to using Callable, yet after reading this I think this could be what should be used instead by OP. – Naman Nov 01 '17 at 15:47
  • 2
    Yep, this is how you do it in pre java 8 as well. It should still work. A lambda expression can probably be used as well together with an interface, https://stackoverflow.com/questions/13604703/how-do-i-define-a-method-which-takes-a-lambda-as-a-parameter-in-java-8 – patrik Nov 01 '17 at 15:49