Monday 8 May 2023

Implement retry handler for a task in Java

Implement an utility class such that, it takes a code snippet and executes with the configured number of retries until it is successful.

 

Find the below working application.


 

RetryableTask.java

package com.sample.app.interfaces;

public interface RetryableTask {  
    /**
     * Block of code to retry
     */
    void execute();
}

RetryHandler.java

package com.sample.app.handler;

import com.sample.app.interfaces.RetryableTask;

public class RetryHandler {
  private int noOfRetries = 0;

  public RetryHandler(int noOfRetries) {
    if (noOfRetries <= 0) {
      throw new IllegalArgumentException("Number of retries is <= 0");
    }

    this.noOfRetries = noOfRetries;
  }

  public void execute(RetryableTask retryableTask) {
    int retries = 0;
    while (true) {
      try {
        retryableTask.execute();
        break;
      } catch (Throwable t) {
        retries++;
        if (retries > this.noOfRetries) {
          System.err.println("Maximum retries finished......");
          throw t;
        }
        System.err.println("Error occurred, retrying another time");
      }
    }
  }

}

RetryTaskDemo.java

package com.sample.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.sample.app.handler.RetryHandler;
import com.sample.app.interfaces.RetryableTask;

public class RetryTaskDemo {

  public static void main(String[] args) {
    RetryableTask task = new RetryableTask() {

      @Override
      public void execute() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String input;
        System.out.println("Enter 'p' to exit successfully, non 'p' to throw an exception");
        try {
          input = br.readLine();
          if ("p".equals(input)) {
            System.out.println("Task executed successfully");
          } else {
            throw new RuntimeException("Task failed");
          }
        } catch (IOException e) {
          e.printStackTrace(System.err);
        }

      }
    };
    
    RetryHandler retryHandler = new RetryHandler(2);
    retryHandler.execute(task);
  }

}

Sample run 1 : Successful scenario

Enter 'p' to exit successfully, non 'p' to throw an exception
p
Task executed successfully

Sample run 2 : Failed scenario

Enter 'p' to exit successfully, non 'p' to throw an exception
p
Task executed successfully

Sample run 2 : Failed scenario
Enter 'p' to exit successfully, non 'p' to throw an exception
f
Error occurred, retrying another time
Enter 'p' to exit successfully, non 'p' to throw an exception
f
Error occurred, retrying another time
Enter 'p' to exit successfully, non 'p' to throw an exception
f
Maximum retries finished......
Exception in thread "main" java.lang.RuntimeException: Task failed
  at com.sample.app.RetryTaskDemo$1.execute(RetryTaskDemo.java:25)
  at com.sample.app.handler.RetryHandler.execute(RetryHandler.java:20)
  at com.sample.app.RetryTaskDemo.main(RetryTaskDemo.java:35)

Sample run 3 : Task successful in given number of retries

Enter 'p' to exit successfully, non 'p' to throw an exception
f
Error occurred, retrying another time
Enter 'p' to exit successfully, non 'p' to throw an exception
f
Error occurred, retrying another time
Enter 'p' to exit successfully, non 'p' to throw an exception
p
Task executed successfully


You may like

Interview Questions

java.util.Date vs java.sql.Date

How to break out of nested loops in Java?

Implementation of Bag data structure in Java

Scanner throws java.util.NoSuchElementException while reading the input

How to get all the enum values in Java?

Extend the thread to check it’s running status

No comments:

Post a Comment