1. import org.json.JSONObject;
  2. import java.util.concurrent.ThreadLocalRandom;
  3. public class JsonRetry {
  4. /**
  5. * Retries the operation on the JSON object a specified number of times.
  6. *
  7. * @param jsonObject The JSON object to operate on.
  8. * @param maxRetries The maximum number of retry attempts.
  9. * @param delayMillis The delay in milliseconds between retries.
  10. * @param operation The operation to perform on the JSON object. Takes a JSONObject and returns void.
  11. * @throws Exception if the operation fails after maxRetries attempts.
  12. */
  13. public static void retryJsonOperation(JSONObject jsonObject, int maxRetries, long delayMillis, Operation operation) throws Exception {
  14. for (int i = 0; i <= maxRetries; i++) {
  15. try {
  16. operation.perform(jsonObject); // Perform the operation
  17. return; // Success, exit the retry loop
  18. } catch (Exception e) {
  19. if (i == maxRetries) {
  20. throw e; // Re-throw the exception if max retries reached
  21. }
  22. long randomDelay = ThreadLocalRandom.current().nextLong(delayMillis); // Introduce random delay
  23. try {
  24. Thread.sleep(randomDelay); // Wait before retrying
  25. } catch (InterruptedException ie) {
  26. Thread.currentThread().interrupt(); // Restore interrupted status
  27. throw new Exception("Retry interrupted", ie);
  28. }
  29. System.out.println("Retry attempt " + (i + 1) + " of " + maxRetries + " failed. Retrying in " + delayMillis + "ms...");
  30. }
  31. }
  32. }
  33. /**
  34. * Functional interface for the operation to be performed on the JSON object.
  35. */
  36. @FunctionalInterface
  37. public interface Operation {
  38. void perform(JSONObject jsonObject);
  39. }
  40. public static void main(String[] args) throws Exception {
  41. // Example Usage
  42. JSONObject jsonObject = new JSONObject();
  43. jsonObject.put("name", "Example");
  44. jsonObject.put("value", 123);
  45. // Define an operation to perform
  46. Operation myOperation = (jsonObject) -> {
  47. System.out.println("Performing operation on JSON object: " + jsonObject.toString());
  48. // Simulate a potential failure
  49. if (ThreadLocalRandom.current().nextBoolean()) {
  50. throw new RuntimeException("Simulated failure");
  51. }
  52. System.out.println("Operation completed successfully.");
  53. };
  54. // Retry the operation with 3 retries and a 1-second delay
  55. retryJsonOperation(jsonObject, 3, 1000, myOperation);
  56. }
  57. }

Add your comment