Monday, 27 April 2020

Implement re-try-catch

Write code such that, you should execute some code snippet. If you got any error while executing the code snippet, sleep for 100 milliseconds and retry ‘N’ times.

Following snippet implements above functionality.
public void retryAndExecuteErrorProneCode(int noOfTimesToRetry, CodeSnippet codeSnippet, int sleepTimeInMillis)
  throws InterruptedException {

 int currentExecutionCount = 0;
 boolean codeExecuted = false;

 while (currentExecutionCount < noOfTimesToRetry) {
  try {
   codeSnippet.errorProneCode();
   System.out.println("Code executed successfully!!!!");
   codeExecuted = true;
   break;
  } catch (Exception e) {
   // Retry after 100 milliseconds
   TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis);
   System.out.println(e.getMessage());
  } finally {
   currentExecutionCount++;
  }
 }

 if (!codeExecuted)
  throw new RuntimeException("Can't execute the code within given retries : " + noOfTimesToRetry);
}

Find the below working application.

CodeSnippet.java
package com.sample.app.lambdas;

public interface CodeSnippet {

 public void errorProneCode();
}

RetryUtil.java
package com.smaple.app.utils;

import java.util.concurrent.TimeUnit;

import com.sample.app.lambdas.CodeSnippet;

public class RetryUtil {
 public void retryAndExecuteErrorProneCode(int noOfTimesToRetry, CodeSnippet codeSnippet, int sleepTimeInMillis)
   throws InterruptedException {

  int currentExecutionCount = 0;
  boolean codeExecuted = false;

  while (currentExecutionCount < noOfTimesToRetry) {
   try {
    codeSnippet.errorProneCode();
    System.out.println("Code executed successfully!!!!");
    codeExecuted = true;
    break;
   } catch (Exception e) {
    // Retry after 100 milliseconds
    TimeUnit.MILLISECONDS.sleep(sleepTimeInMillis);
    System.out.println(e.getMessage());
   } finally {
    currentExecutionCount++;
   }
  }

  if (!codeExecuted)
   throw new RuntimeException("Can't execute the code within given retries : " + noOfTimesToRetry);
 }

}

App.java
package com.sample.app;

import java.util.Random;

import com.smaple.app.utils.RetryUtil;

public class App {

 public static void main(String args[]) throws InterruptedException {
  RetryUtil retryUtil = new RetryUtil();
  retryUtil.retryAndExecuteErrorProneCode(3, () -> {
   Random rand = new Random();

   int randVal = rand.nextInt(50);

   if (randVal <= 10) {
    return;
   }

   throw new RuntimeException("Service Unavailable");
  }, 100);
 }

}

Sample Output 1
Service Unavailable
Service Unavailable
Service Unavailable
Exception in thread "main" java.lang.RuntimeException: Can't execute the code within given retries : 3
         at com.smaple.app.utils.RetryUtil.retryAndExecuteErrorProneCode(RetryUtil.java:30)
         at com.sample.app.App.main(App.java:11)


Sample Output 2
Code executed successfully!!!!

Sample Output 3
Service Unavailable
Service Unavailable
Code executed successfully!!!!




You may like

No comments:

Post a Comment