import org.json.JSONObject;
import java.util.concurrent.ThreadLocalRandom;
public class JsonRetry {
/**
* Retries the operation on the JSON object a specified number of times.
*
* @param jsonObject The JSON object to operate on.
* @param maxRetries The maximum number of retry attempts.
* @param delayMillis The delay in milliseconds between retries.
* @param operation The operation to perform on the JSON object. Takes a JSONObject and returns void.
* @throws Exception if the operation fails after maxRetries attempts.
*/
public static void retryJsonOperation(JSONObject jsonObject, int maxRetries, long delayMillis, Operation operation) throws Exception {
for (int i = 0; i <= maxRetries; i++) {
try {
operation.perform(jsonObject); // Perform the operation
return; // Success, exit the retry loop
} catch (Exception e) {
if (i == maxRetries) {
throw e; // Re-throw the exception if max retries reached
}
long randomDelay = ThreadLocalRandom.current().nextLong(delayMillis); // Introduce random delay
try {
Thread.sleep(randomDelay); // Wait before retrying
} catch (InterruptedException ie) {
Thread.currentThread().interrupt(); // Restore interrupted status
throw new Exception("Retry interrupted", ie);
}
System.out.println("Retry attempt " + (i + 1) + " of " + maxRetries + " failed. Retrying in " + delayMillis + "ms...");
}
}
}
/**
* Functional interface for the operation to be performed on the JSON object.
*/
@FunctionalInterface
public interface Operation {
void perform(JSONObject jsonObject);
}
public static void main(String[] args) throws Exception {
// Example Usage
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "Example");
jsonObject.put("value", 123);
// Define an operation to perform
Operation myOperation = (jsonObject) -> {
System.out.println("Performing operation on JSON object: " + jsonObject.toString());
// Simulate a potential failure
if (ThreadLocalRandom.current().nextBoolean()) {
throw new RuntimeException("Simulated failure");
}
System.out.println("Operation completed successfully.");
};
// Retry the operation with 3 retries and a 1-second delay
retryJsonOperation(jsonObject, 3, 1000, myOperation);
}
}
Add your comment