-2

I'm trying to apply retry logic to a number of methods. For example, I have method1(String) and method2(int, String) that I would like to retry up to a certain number of times.

I would ideally like:

int count = 0;
while (count < MAX_TRIES) {
    try { 
        //run method
    } catch (Exception e) {
        //increment count
        //throw e if count == MAX_TRIES
    }
}

inside a method where I could pass in as a parameter method1 or method2. Is there any way to do this? Thanks!

User9123
  • 69
  • 2
  • 10
  • 2
    what do you mean by `inside method or class`? can you please be more specific – Ryuzaki L Sep 28 '18 at 23:57
  • I'm not sure I follow the question, but one way to "pass" a method is to create an `interface`, where there are alternative implementations of a given method, and then one invokes the specific method name. – KevinO Sep 28 '18 at 23:59
  • There is an existing code base that has a lot of function calls that need to be retried. I just want to be able to pass in those functions whenever they're called to a function that will retry them rather than surrounding these calls with the above retry logic. – User9123 Sep 29 '18 at 00:07
  • Similar to Command design pattern. You need 2 commands and one command executor. – Pavel Molchanov Sep 29 '18 at 02:18

1 Answers1

1

Sure:

public <T> T retry(Callable<T> callable) throws Exception {
    int count = 0;
    while (true) {
        try { 
            return callable.call();
        } catch (Exception e) {
            count++;
            if (count == MAX_TRIES) {
                throw(e);
            }
        }
    }
}

And then

retry(() -> doSomething(a, b));
retry(() -> doSomethingElse(a));

This simple implementation is not very flexible, and could use better exception handling, though. You could use a library to do that (disclaimer: I'm the original author of this library), or at least see how it works and reuse some of its ideas.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • You forgot to `return` a value. When you do, you'd also realize that the loop should be a forever loop, e.g. `for (;;)` or `while (true)`. – Andreas Sep 29 '18 at 00:39
  • Oops. Yes. Fixed now. Or we could throw an IllegalStateException after the loop. Thanks. – JB Nizet Sep 29 '18 at 06:26