Pattern for Try Catch Do Again

Retry Designing!

Retry Designing is a critical use instance of any application so that applications are mistake tolerant.

The application can run into a number of issues, where in that location could be a failure momentarily. The same operation when performed again generally resolves the error. The performance of performing those repetitive tasks again so that the awarding works without any issues, is what a Retry machinery is.

Unavailable services, unreachable networks, unable to consummate an functioning are some examples where nosotros demand Retry Designing.

Patterns in retry Designing :

Continuous Retry : If an operation fails, we again effort to perform the same operation immediately

Retry after an interval : If an operation fails, we will perform the same functioning afterwards an interval.

Stop and return : If any of the operations neglect, and then we retry the same operation. However the question is until when ? — So we utilize an integer counter variable and then that operations are tried for a number of times, and if it is still throwing an error subsequently the number of attempts, and then we throw a user defined mistake and then that a user knows about the fault.

This case is in Coffee 8

Cosmos of file (fail prophylactic) :

Note : The below code is not the best design, notwithstanding it is uncomplicated to understand. And so at the cease of the blog I have provided the code with skillful design.

We are trying to create file. If the operation is non successful, we are trying it again until retry variable (which is 5). The operation here is to create a file, however it could be annihilation in your case like a database connectivity.

In the below lawmaking, we are trying to create a directory in try block, yet if it fails we will again try information technology in the catch block. We accept used a while loop and then that we can try this operation for a number of times. At the end we accept used an if block, which is a validation cheque to come across if the directories were not created even after all attempts. If yes, then we throw an mistake.

          import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public course App {
public static void main(String[] args) throws IOException {
dirCreation();
}

static void dirCreation() throws IOException{
String directoryPath = "/temporary/blogs/";
attempt {
Files.createDirectories(Paths.become(directoryPath));
} catch (Exception e) {
int retry = 5;
while(!Files.exists(Paths.get(directoryPath))
&& retry!=0) {
retry--;
Files.createDirectories(Paths.get(directoryPath));
}
if(!Files.exists(Paths.go(directoryPath))) {
throw new IOException();
}
}
}

}

The problem with to a higher place design is that, our concern logic is also available in catch cake; which should non exist the case. One more than effect it that the above logic is not reusable. If we wanted to apply the above logic to retry for database connectivity, we would accept to write the logic again.

And so the beneath approach volition use a dissimilar class for Retry logic, and we will pass our business use example as a lambda(lawmaking equally function) to the retry form. Hence using this arroyo we can use the aforementioned RetryLogic course for any purpose we want.

A functional interface to accept lambdas -

RetryImplementation.coffee

          import coffee.io.IOException;

@FunctionalInterface
public interface RetryImplementation {
Boolean run() throws IOException;
}

We have 2 variables hither. One retryAttempts, for the number of retries; other TIME_TO_WAIT, for the interval betwixt two retries.
retryImpl() takes the core method which is to be fabricated fault tolerant and retried a number of times. It accepts a method implementation.

RetryLogic.java

          import coffee.io.IOException;

public class RetryLogic {

int retryAttempts;
final long TIME_TO_WAIT;

RetryLogic(int retryAttempts, long timeToWait) {
this.retryAttempts = retryAttempts;
this.TIME_TO_WAIT = timeToWait;
}

public void retryImpl(RetryImplementation retryImplementation) throws IOException {
if (shouldRetry()) {
retryAttempts--;
retryImplementation.run();
waitBeforeNextRetry();
} else {

throw new IOException();
}

}
public boolean shouldRetry() {
return retryAttempts > 0;
}
public void waitBeforeNextRetry() {
effort {
Thread.sleep(TIME_TO_WAIT);
} grab (Exception e) {
}
}
}

In the below code, we are passing the retry logic to retryImpl every bit lambda(Java 8). The lawmaking is generic as you can pass your ain employ case like database connectivity retries or whatever code which needs neglect rubber tolerance.

App.coffee

          import java.io.IOException;

public class App {
static Cord directoryPath = "/temporary/blogs";
static RetryLogic retryLogic = new RetryLogic(5, 2000);
public static void principal(String[] args) throws IOException {
dirCreation();

}

static void dirCreation() throws IOException {
try {
Files.createDirectories(Paths.get(directoryPath));

} catch (Exception east) {
retryLogic.retryImpl(() -> {
try {
dirCreation();
} finally {

}
return zero;
})

;
}
}
}

Conclusion

All the claps and follows are highly appreciated. Thanks !

parksweas1991.blogspot.com

Source: https://medium.com/javarevisited/retry-pattern-fail-safe-strategy-2244f6bd247c

0 Response to "Pattern for Try Catch Do Again"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel