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

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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, stackoverflow.com/questions/13604703/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.