|
1 | | -/* |
2 | | - * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). |
3 | | - * |
4 | | - * The MIT License |
5 | | - * Copyright © 2014-2022 Ilkka Seppälä |
6 | | - * |
7 | | - * Permission is hereby granted, free of charge, to any person obtaining a copy |
8 | | - * of this software and associated documentation files (the "Software"), to deal |
9 | | - * in the Software without restriction, including without limitation the rights |
10 | | - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
11 | | - * copies of the Software, and to permit persons to whom the Software is |
12 | | - * furnished to do so, subject to the following conditions: |
13 | | - * |
14 | | - * The above copyright notice and this permission notice shall be included in |
15 | | - * all copies or substantial portions of the Software. |
16 | | - * |
17 | | - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
18 | | - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
19 | | - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
20 | | - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
21 | | - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
22 | | - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
23 | | - * THE SOFTWARE. |
24 | | - */ |
25 | 1 | package com.iluwatar.commander; |
26 | 2 |
|
27 | | -import java.security.SecureRandom; |
28 | | -import java.util.ArrayList; |
29 | | -import java.util.Arrays; |
30 | | -import java.util.List; |
| 3 | +import java.util.*; |
| 4 | +import java.util.concurrent.ThreadLocalRandom; |
31 | 5 | import java.util.concurrent.atomic.AtomicInteger; |
32 | 6 | import java.util.function.Predicate; |
33 | 7 |
|
34 | 8 | /** |
35 | | - * Retry pattern. |
| 9 | + * Retry class that applies the retry pattern with customizable backoff and error handling. |
36 | 10 | * |
37 | | - * @param <T> is the type of object passed into HandleErrorIssue as a parameter. |
| 11 | + * @param <T> The type of object passed into HandleErrorIssue as a parameter. |
38 | 12 | */ |
39 | | - |
40 | 13 | public class Retry<T> { |
41 | 14 |
|
42 | 15 | /** |
43 | | - * Operation Interface will define method to be implemented. |
| 16 | + * Operation interface for performing the core operation. |
44 | 17 | */ |
45 | | - |
46 | 18 | public interface Operation { |
47 | 19 | void operation(List<Exception> list) throws Exception; |
48 | 20 | } |
49 | 21 |
|
50 | 22 | /** |
51 | | - * HandleErrorIssue defines how to handle errors. |
| 23 | + * HandleErrorIssue defines how to handle errors during retries. |
52 | 24 | * |
53 | | - * @param <T> is the type of object to be passed into the method as parameter. |
| 25 | + * @param <T> The type of object passed into the method as a parameter. |
54 | 26 | */ |
55 | | - |
56 | 27 | public interface HandleErrorIssue<T> { |
57 | 28 | void handleIssue(T obj, Exception e); |
58 | 29 | } |
59 | 30 |
|
60 | | - private static final SecureRandom RANDOM = new SecureRandom(); |
| 31 | + /** |
| 32 | + * BackoffStrategy defines the strategy for calculating retry delay. |
| 33 | + */ |
| 34 | + public interface BackoffStrategy { |
| 35 | + long calculateDelay(int attempt); |
| 36 | + } |
61 | 37 |
|
62 | | - private final Operation op; |
63 | | - private final HandleErrorIssue<T> handleError; |
| 38 | + private final Operation operation; |
| 39 | + private final HandleErrorIssue<T> errorHandler; |
64 | 40 | private final int maxAttempts; |
65 | | - private final long maxDelay; |
| 41 | + private final BackoffStrategy backoffStrategy; |
| 42 | + private final Predicate<Exception> ignoreCondition; |
66 | 43 | private final AtomicInteger attempts; |
67 | | - private final Predicate<Exception> test; |
68 | | - private final List<Exception> errors; |
| 44 | + private final List<Exception> errorList; |
69 | 45 |
|
70 | | - Retry(Operation op, HandleErrorIssue<T> handleError, int maxAttempts, |
71 | | - long maxDelay, Predicate<Exception>... ignoreTests) { |
72 | | - this.op = op; |
73 | | - this.handleError = handleError; |
| 46 | + /** |
| 47 | + * Constructor for Retry class. |
| 48 | + * |
| 49 | + * @param operation The operation to retry. |
| 50 | + * @param errorHandler The handler for errors. |
| 51 | + * @param maxAttempts The maximum number of retry attempts. |
| 52 | + * @param backoffStrategy The backoff strategy for retry delays. |
| 53 | + * @param ignoreCondition A predicate to determine whether to ignore certain exceptions. |
| 54 | + */ |
| 55 | + public Retry(Operation operation, HandleErrorIssue<T> errorHandler, int maxAttempts, |
| 56 | + BackoffStrategy backoffStrategy, Predicate<Exception> ignoreCondition) { |
| 57 | + this.operation = operation; |
| 58 | + this.errorHandler = errorHandler; |
74 | 59 | this.maxAttempts = maxAttempts; |
75 | | - this.maxDelay = maxDelay; |
76 | | - this.attempts = new AtomicInteger(); |
77 | | - this.test = Arrays.stream(ignoreTests).reduce(Predicate::or).orElse(e -> false); |
78 | | - this.errors = new ArrayList<>(); |
| 60 | + this.backoffStrategy = backoffStrategy; |
| 61 | + this.ignoreCondition = ignoreCondition; |
| 62 | + this.attempts = new AtomicInteger(0); |
| 63 | + this.errorList = new ArrayList<>(); |
79 | 64 | } |
80 | 65 |
|
81 | 66 | /** |
82 | | - * Performing the operation with retries. |
| 67 | + * Perform the operation with retries. |
83 | 68 | * |
84 | | - * @param list is the exception list |
85 | | - * @param obj is the parameter to be passed into handleIsuue method |
| 69 | + * @param exceptions The list of exceptions encountered during retries. |
| 70 | + * @param obj The object passed to the error handler. |
86 | 71 | */ |
87 | | - |
88 | | - public void perform(List<Exception> list, T obj) { |
| 72 | + public void perform(List<Exception> exceptions, T obj) { |
89 | 73 | do { |
90 | 74 | try { |
91 | | - op.operation(list); |
92 | | - return; |
| 75 | + operation.operation(exceptions); |
| 76 | + return; // Exit if successful |
93 | 77 | } catch (Exception e) { |
94 | | - this.errors.add(e); |
95 | | - if (this.attempts.incrementAndGet() >= this.maxAttempts || !this.test.test(e)) { |
96 | | - this.handleError.handleIssue(obj, e); |
97 | | - return; //return here... don't go further |
| 78 | + errorList.add(e); |
| 79 | + |
| 80 | + if (attempts.incrementAndGet() >= maxAttempts || !ignoreCondition.test(e)) { |
| 81 | + errorHandler.handleIssue(obj, e); |
| 82 | + return; // Stop retrying if max attempts are exceeded or exception is non-recoverable |
98 | 83 | } |
| 84 | + |
99 | 85 | try { |
100 | | - long testDelay = |
101 | | - (long) Math.pow(2, this.attempts.intValue()) * 1000 + RANDOM.nextInt(1000); |
102 | | - long delay = Math.min(testDelay, this.maxDelay); |
| 86 | + long delay = backoffStrategy.calculateDelay(attempts.intValue()); |
103 | 87 | Thread.sleep(delay); |
104 | | - } catch (InterruptedException f) { |
105 | | - //ignore |
| 88 | + } catch (InterruptedException ie) { |
| 89 | + Thread.currentThread().interrupt(); // Restore interrupted status |
| 90 | + errorHandler.handleIssue(obj, new RuntimeException("Thread interrupted during retry", ie)); |
| 91 | + return; |
106 | 92 | } |
107 | 93 | } |
108 | 94 | } while (true); |
109 | 95 | } |
110 | 96 |
|
| 97 | + /** |
| 98 | + * Returns an unmodifiable list of errors encountered during retries. |
| 99 | + * |
| 100 | + * @return A list of encountered errors. |
| 101 | + */ |
| 102 | + public List<Exception> getErrorList() { |
| 103 | + return Collections.unmodifiableList(errorList); |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * Default ExponentialBackoffStrategy with jitter. |
| 108 | + */ |
| 109 | + public static class ExponentialBackoffWithJitter implements BackoffStrategy { |
| 110 | + private final long maxDelay; |
| 111 | + |
| 112 | + public ExponentialBackoffWithJitter(long maxDelay) { |
| 113 | + this.maxDelay = maxDelay; |
| 114 | + } |
| 115 | + |
| 116 | + @Override |
| 117 | + public long calculateDelay(int attempt) { |
| 118 | + long baseDelay = (long) Math.pow(2, attempt) * 1000; |
| 119 | + return Math.min(baseDelay + ThreadLocalRandom.current().nextInt(1000), maxDelay); |
| 120 | + } |
| 121 | + } |
111 | 122 | } |
0 commit comments