mechanism of "run" method of failsafe

1.1k Views Asked by At

I am using Failsafe (https://github.com/jhalterman/failsafe) as my retry logic framework and want to know more of how "run" method of failsafe works.

Suppose I have:

void MyCurrentFunction(parameter) {
    Failsafe.with(MY_RETRY_POLICY)
            .run(() -> runJob(parameter));
    OtherFunction1();
}

Then when MyCurrentFunction runs, will Failsafe.run blocks execution of MyCurrentFunction? In other words, will OtherFunction1 be executed before all retries finishes?

1

There are 1 best solutions below

0
On

Here is code that checks your question (Note: the code is related Failsafe 2.0)

private RetryPolicy<Object> MY_RETRY_POLICY = new RetryPolicy<>()
        .handle(RuntimeException.class)
        .withMaxRetries(3);

private void myCurrentFunction() {
    Failsafe.with(MY_RETRY_POLICY)
            .run(() -> runJob());

    otherFunction1();
}

private void otherFunction1() {
    System.out.println("OtherFunction1");
}

private void runJob() {
    System.out.println("run job...");

    throw new RuntimeException("Exception");
}

The answer is No; OtherFunction1 will not be executed before all retries finishes.
Actually, if all retries fail OtherFunction1 will never be invoked.

Here is the output for test code

run job...
run job...
run job...
run job...

java.lang.RuntimeException: Exception

Still, you can modify the retry policy to execute OtherFunction1
1) After each retry

private RetryPolicy<Object> MY_RETRY_POLICY = new RetryPolicy<>()
        .handle(RuntimeException.class)
        .onRetry(fail -> otherFunction1())
        .withMaxRetries(3);

2) After retries fail

private RetryPolicy<Object> MY_RETRY_POLICY = new RetryPolicy<>()
        .handle(RuntimeException.class)
        .onFailure(fail -> otherFunction1())
        .withMaxRetries(3);