I am trying to write a retry mechanism in java, that reties a function after 3 minutes in case of failure, and retries up to maximum 3 times. I do not want to use Thread.Sleep, and instead I was thinking about using ScheduledExecutorService. I am trying to figure out what would be a good implementation for it. It seems executor.schedule() does not the runnable inside the runnable.
I was thinking something like this:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
final int count = 1;
final int MAX_RETRY = 3;
Runnable runnable = () -> {
try {
//This function can fail and throw FunctionException
callMyFunction();
}
catch (FunctionException e) {
if (++count <= MAX_RETRY) {
executor.schedule(runnable, 30*60*1000);
}
}
};
executor.execute(runnable);
I would suggest you use the spring-retry library instead of writing your own implementation.
Create a RetryTemplate instance. Sample code here - https://github.com/innovationchef/batchpay/blob/master/src/main/java/com/innovationchef/service/PayApiRetryTemplate.java
Then call you method like this -
retryTemplate.execute(arg -> callMyFunction());
This code seems to work, and resolves the issue I had. I could not use lambda to implement my Runnable function, as in lambda there is no way to have "this" reference the instance created by a lambda expression in this line:
scheduler.schedule(this, 1, TimeUnit.SECONDS);
Any idea how to fix that?
Here is the entire code:
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
AtomicInteger counter = new AtomicInteger(1);
final int MAX_RETRY = 3;
scheduler.execute(new Runnable() {
@Override
public void run () {
try {
System.out.println("Attempt number: " + counter.get());
functionCall();
scheduler.shutdown();
}
catch (Exception e) {
if (counter.get() < MAX_RETRY) {
System.out.println("Attempt number: " + counter.getAndIncrement() + " failed.");
scheduler.schedule(this, 1, TimeUnit.SECONDS);
}
else {
System.out.println("Error message: " + e.getMessage());
scheduler.shutdown();
}
}
}
});
}
public static void functionCall() {
throw new RuntimeException("Does not work");
}
Thanks @Turing85 for the help and useful comments.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.